Reputation: 162
I'm trying to edit some filenames with padded 0s from the command line. I want T9 to become T009 for example.
I tried:
@echo off
set num=99
set newnum=000%num%
set newnum=%newnum:~-4%
rename "T%num%.bmp" "T%newnum%.bmp"
pause
which did indeed changed file t99.bmp to T0099.bmp as I expected. However, when I try a loop like:
@echo off
FOR /L %%G IN (1,1,100) DO (
set num=%%G
echo %%G
set newnum=0000%num%
set newnum=%newnum:~-4%
echo %newnum%
ren "T%num%.bmp" "T%newnum%.bmp"
)
pause
It tells me that 'ECHO is off' and 'The system cannot find the file specified.' Note, it DOES echo %%G so I have no clue what's going on. I think it has something to do with being inside the loop? But I haven't been able to figure that out by googling.
My overall question is: Is there an obvious mistake in my methodology? and Why does the first chunk of code behave as I expect, but not the second?
I just learned batch like an hour ago and so far it's given me a headache. haha.
Upvotes: 1
Views: 120
Reputation: 2277
Set EnableDelayedExpansion
then reference the variables with !var!
instead of %var%
Fixed code:
@echo off
setlocal EnableDelayedExpansion
FOR /L %%G IN (1,1,100) DO (
set num=%%G
echo !num!
set newnum=0000!num!
set newnum=!newnum:~-4!
echo !newnum!
ren "T%%G.bmp" "T!newnum!.bmp"
)
pause
endlocal
ECHO IS OFF
will appear if the variable you are attempting to echo is empty.
For the file not found part, that simply means that the file you are attempting to process is not found. Make sure the .bat
file is in the same folder as the .bmp
image's. If not, either move it there or cd your way to the path.
To read more about EnableDelayedExpansion, click here
Also, just to let you know, setting the num
variable as you did is unnecessary, set newnum=0000%%G
would work fine.
Upvotes: 1