Search code examples
batch-fileleading-zerozero-pad

Windows batch folder loop with padding


I'm wanting to write a batch script to loop over a set of files that have a zero pad on them. I'm having problems with using set as it seems to be using the last number in my iteration as the value that should be used. Here is what I have:

 @echo off
for /L %%r in (1,1,%1) do (
echo %%r
set "var=00%%r"
echo %var%
)

When running this with an input of 5 I get this as output:

1
005
2
005
3
005
4
005
5
005

I would like it to be:

1
001
2
002
3
003
4
004
5
005

Any help on this would be great. Thanks.


Solution

  • You really should read on the topic delayed expansion. The vars in a (code block) are evaluated only once when cmd.exe parses the content. Where does that $1 come from? Should it be %1? If you want to have a fixed length number with leading zeroes you should keep mind that "Set /A " treats numbers with leading zeroes as octal numbers. This is a work around

    @echo off
    Setlocal EnableDelayedExpansion
    for /L %%r in (1,1,5) do (
      Set /A var=1000+%%r
      Call echo Pseudo Call %%var:~-3%% %%r
      echo Delayed expansion with exclamation mark !var:~-3! %%r
    )
    

    You see 2 different methods to get the actual value of var

    Pseudo Call 001 1
    Delayed expansion with exclamation mark 001 1
    Pseudo Call 002 2
    Delayed expansion with exclamation mark 002 2
    Pseudo Call 003 3
    Delayed expansion with exclamation mark 003 3
    Pseudo Call 004 4
    Delayed expansion with exclamation mark 004 4
    Pseudo Call 005 5
    Delayed expansion with exclamation mark 005 5