0

I am attempting to change filenames in a directory to the same file type but with incrementing values as the filename. For example let's say I have a directory title "pics" that has the following files:

pic1.png
pic2.png
pic3.png

I want to rename the files to:

1.png
2.png
3.png

Here's the code I tried to run on the file to do this. I set the variable "i" to 0 before running this (I'm using the command prompt, which is why I'm using "%g" instead of "%%g"):

for %g in (*.png) do (
    set /a i+=1
    ren %g %i%.png
)

What happens is that pic1.png successfully gets changed to 1.png, but then the program tries to rename pic2.png and pic3.png to 1.png. I want them to be renamed to 2.png and 3.png respectively. What am I doing wrong?

lit
  • 14,456
  • 10
  • 65
  • 119
doy
  • 11
  • 3
  • I think you want to do `set /a i+=1`. EDIT: This is probably crucial too: http://www.dreamincode.net/forums/topic/40896-using-set-a-statements-in-windows-batch-file/. Apparently, the variable won't increment until after the for closing. Meaning, if you were to print outside of the for loop, the value would be 3.png. – Jacob Barnes Nov 22 '17 at 21:02
  • I meant to have it as: `set /a i+=1` Still doesn't work if I put /a, and yeah it seems like the number doesn't increment inside the for loop. – doy Nov 22 '17 at 21:06
  • You need to use delayed variable expansion. I will write up an answer, but essentially it is a `cmd /v` when your executing the batch file and a little code refactoring . – Jacob Barnes Nov 22 '17 at 21:08
  • Actually, feeling lazy, but this should resolve you issue: http://www.dreamincode.net/forums/topic/40896-using-set-a-statements-in-windows-batch-file/ – Jacob Barnes Nov 22 '17 at 21:11
  • I tried running the following code: `set i=1 for %%g in (*.bmp) do ( ren %g %i%.bmp set /a i=i+1 )` – doy Nov 22 '17 at 21:22
  • I can't edit my previous comment for some reason, so I'll post my full comment here: I tried running the following code: `set i=1 for %%g in (*.bmp) do ( ren %g %i%.bmp set /a i=i+1 )` But I'm not sure how to run it in the command line with the /v argument. I try using `code /v' but that just runs the code normally. I tried `/v code` but that gives me a syntax error. – doy Nov 22 '17 at 21:31
  • @doy - Edit the question to show the code you are trying. It is exceedingly difficult to try to read a block of code in a comment. – lit Nov 23 '17 at 03:05
  • if you *really* need to do it directly on command line, you need to open a new `cmd` instance with `cmd /v:on` to enable delayed expansion (by default it is turned off) – Stephan Nov 23 '17 at 07:05
  • Oh thank you Mofi for the software suggestions! I'm trying out IrfanView right now. And Stephan, I'll try that as well. – doy Nov 23 '17 at 22:05

0 Answers0