Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Win bat file: How to add leading zeros to a variable in a for loop? [duplicate]

Very simple, I guess... I need to get a usable variable by adding leading zeros to the loop index variable (%%i) below.

@echo off
for /L %%i in (1, 1, 5) do (
     echo %%i

     rem     How to create a variable j here as a 
     rem     result of adding leading zeros to %%i? (001, 002, 003 etc.)

)
pause

How? I've tried the following, but I can't get the value out of the %%i variable inte the var_ at a...

@echo off & setlocal enableextensions
for /L %%i in (1, 1, 5) do (
     echo %%i
     set var_=00000%%i
     set var_=%var_:~-5%
     echo %var_%
)
pause
like image 994
Cambiata Avatar asked Feb 24 '12 12:02

Cambiata


People also ask

How do you add leading zeros to a variable?

If the variable in which you want to add leading zeros contains only numeric values, we can simply use Zw. d format. In this case, we made length of the newly transformed variable as 6.

What is %% A in batch script?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.


2 Answers

Prefix the string with zeros and then take the desired count of characters from the right side:

@echo off
set count=5
setlocal EnableDelayedExpansion

for /L %%i in (1, 1, %count%) do (
     set "formattedValue=000000%%i"
     echo !formattedValue:~-3!
)

Outputs:

001
002
003
004
005
like image 113
jeb Avatar answered Sep 20 '22 02:09

jeb


Using the setlocal enabledelayedexpansion, the solution is this:

@echo off
setlocal ENABLEDELAYEDEXPANSION
set count=5

for /L %%i in (1, 1, %count%) do (
     echo %%i
     set j=00%%i
  rem to display intermediate values inside loop, surround with !
     echo !j!
)
endlocal

Here is a good reference: http://blog.crankybit.com/why-that-batch-for-loop-isnt-working/

like image 28
vaisakh Avatar answered Sep 20 '22 02:09

vaisakh