Andrew Backes
Andrew Backes

Reputation: 1904

Batch File If statement inside For loop

I am having the issue where my if statement (inside a for loop), doesn't seem to cooperate. What I am trying to do is this:

Here is what I have thus far:

setlocal enableextensions enabledelayedexpansion
SET /a COUNT=5
SET FILE_PREFIX=00
SET /a MAX=10
for %%f in (*.zip) do  (
   if !COUNT! == !MAX! (set FILE_PREFIX=0)
   ren "%%f" %FILE_PREFIX%!COUNT!.zip
   set /a COUNT+=1
   echo !COUNT!
)
endlocal

Why doesn't the if statement work? The file renaming is working fine, it is just that if statement that doesn't change the FILE_PREFIX to 0.

Upvotes: 1

Views: 9453

Answers (1)

PA.
PA.

Reputation: 29369

The problem is that your code doesnt apply delayed expansion to the FILE_PREFIX so the value is calculated just once in the loop, at parse time; instead of being refreshed every iteration at runtime.

Just change your line to

ren "%%f" !FILE_PREFIX!!COUNT!.zip

and presto! it should work.

But once you correct it, still your method would fail for numbers above 999.

For a more robust implementation, try this alternative

SET /a count=1
for %%f in (*.zip) do  (
  set fn=0000!count!
  echo REN "%%f" !fn:~-4!%%~xf
  set /a count+=1
)

Inside the loop

  1. the code 0000!count! appends some zeros (4 in this case) to the number; so it will follow the sequence 00001, 00002, ... 00009, 000010, 000011, ...

  2. then !fn:~-4! removes all digits but the last N (4 in this example). So it will follow the desired sequence 0001, 0002, ... 0009, 0010, 0011, ...

  3. and %%~xf extracts the extension (.zip in all the cases of this loop) and appends it to form the final filename. So it will follow the desired sequence 0001.zip, 0002.zip, ... 0009.zip, 0010.zip, 0011.zip, ...

This method will work for any number up to 9999. You can easily extend it to 5 o 6 or even more digits.

Upvotes: 3

Related Questions