Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String processing in windows batch files: How to pad value with leading zeros?

in a Windows cmd batch file (.bat), how do i pad a numeric value, so that a given value in the range 0..99 gets transformed to a string in the range "00" to "99". I.e. I'd like to having leading zeros for values lower than 10.

like image 217
Scrontch Avatar asked Nov 15 '12 13:11

Scrontch


People also ask

What is %% K in batch file?

So %%k refers to the value of the 3rd token, which is what is returned.

How do you handle spaces in a batch file?

When you send arguments, those with poison or space characters need to be doublequoted. Inside your batch file, if you no longer need the surrounding doublequotes, you'd remove them by using %~5 instead of %5 . Additionally the recommended syntax for the set command is Set "VariableName=VariableValue" .

How do you make a batch file that opens a program maximized?

A START command is used to run a program or command in a separate window from a Windows command prompt (CMD). The new window can be started as maximized or minimized, that can be controlled using the /MAX or /MIN switches correspondingly.


1 Answers

There's a two-stage process you can use:

REM initial setup SET X=5  REM pad with your desired width - 1 leading zeroes SET PADDED=0%X%  REM slice off any zeroes you don't need -- BEWARE, this can truncate the value REM the 2 at the end is the number of desired digits SET PADDED=%PADDED:~-2% 

Now TEMP holds the padded value. If there's any chance that the initial value of X might have more than 2 digits, you need to check that you didn't accidentally truncate it:

REM did we truncate the value by mistake? if so, undo the damage SET /A VERIFY=1%X% - 1%PADDED% IF NOT "%VERIFY%"=="0" SET PADDED=%X%  REM finally update the value of X SET X=%PADDED% 

Important note:

This solution creates or overwrites the variables PADDED and VERIFY. Any script that sets the values of variables which are not meant to be persisted after it terminates should be put inside SETLOCAL and ENDLOCAL statements to prevent these changes from being visible from the outside world.

like image 192
Jon Avatar answered Oct 24 '22 15:10

Jon