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

39,507

Solution 1

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

Solution 2

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/

Share:
39,507
Cambiata
Author by

Cambiata

Updated on July 09, 2022

Comments

  • Cambiata
    Cambiata almost 2 years

    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