-1

I've written a batch file that is supposed make a number of folders, numbered from 1 to 20, and pad numbers less than 10 with 0. It creates the folders, but doesn't pad them, i.e. 1,2,3..., but I want it to be 01,02,03.

FOR /L %%G IN (1,1,20) DO (
    IF %%G LSS 10 (
      SET J=0
      md %J%%%G
    ) ELSE (
      SET J=""
      md %J%%%G
    )
)
@pause
Derp
  • 33
  • 4
  • 1
    For something so quick and trivial, I don't see any reason why two lines would be much of an issue, `1.` `@FOR /L %%A IN (1,1,9) DO @MD 0%%A 2>NUL`, `2.` `@FOR /L %%A IN (10,1,20) DO @MD %%A 2>NUL` Of course, it could be done using `(101,1,120)` then parsing the result to remove the first character, but it really isn't worth the extra effort. – Compo Jan 27 '19 at 09:43
  • @Compo is competely right. But to answer your question: [see here](https://stackoverflow.com/a/30284028/2152082) – Stephan Jan 27 '19 at 09:56
  • [Cmd : not evaluating variables inside a loop](https://stackoverflow.com/q/3987582/995714), [Why is no string output with 'echo %var%' after using 'set var = text' on command line?](https://stackoverflow.com/q/26386697/995714), [How to set a variable inside a loop for /F](https://stackoverflow.com/q/13805187/995714), [Windows CMD - set within for loop is not working](https://stackoverflow.com/q/12423238/995714)... – phuclv Jan 27 '19 at 11:37
  • Compo, I originally did it with two lines, and it worked, but this was more of a curiosity. Anyway, thanks for the more compact lines. @Stephan Exactly what I needed, thanks. I just set *delayedexpansion* and used ! instead of % in the code above and it worked. – Derp Jan 27 '19 at 23:40

1 Answers1

0

A simple idea, by using two lines, as per my comment:

@FOR /L %%A IN (1,1,9) DO @MD 0%%A 2>NUL
@FOR /L %%A IN (10,1,20) DO @MD %%A 2>NUL

You can also do this in one line by not setting variables unnecessarily:

 @FOR /L %%A IN (1,1,20) DO @IF %%A LSS 10 (MD 0%%A 2>NUL) ELSE MD %%A 2>NUL

Or you could set the variable before the loop:

@SET "J=0"
@FOR /L %%A IN (1,1,20) DO @IF %%A LSS 10 (MD "%J%%%A" 2>NUL) ELSE MD %%A 2>NUL

You could still set the variable in the loop and force expand it using Call:

@FOR /L %%A IN (1,1,20) DO @IF %%A LSS 10 (SET "J=0" && CALL MD "%%J%%%%A" 2>NUL) ELSE MD %%A 2>NUL

Or expand it using delayed expansion:

@SETLOCAL ENABLEDELAYEDEXPANSION
@FOR /L %%A IN (1,1,20) DO @IF %%A LSS 10 (SET "J=0" && MD "!J!%%A" 2>NUL) ELSE MD %%A 2>NUL

And you could parse the results to remove the leading 1:

@FOR /L %%A IN (101,1,120) DO @SET "VAR=%%A" && CALL MD "%%VAR:~-2%%" 2>NUL

Or using delayed expansion:

@SETLOCAL ENABLEDELAYEDEXPANSION
@FOR /L %%A IN (101,1,120) DO @SET "VAR=%%A" && MD !VAR:~-2! 2>NUL
Compo
  • 36,585
  • 5
  • 27
  • 39
  • Thanks for the various ways to do it, but following @Stephan's answer above fixed my code. – Derp Jan 27 '19 at 23:48