Questions

Answer for:

Renaming JPG Files With a Batch File

Message 5 of 6

View entire thread
+
0 Votes
HavaCigar

The SET commands won't take effect until the FOR loop is exited.

You can get around this with a SETLOCAL command. And, since you have nested loops, you need two SETLOCAL commands. When you use SETLOCAL, the references to environment variables need to change from % to !.

Try the following. I left in multiple variables for the filenames for clarity:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%V IN (D:\test\*.jpg) DO (
FOR /F "tokens=1-5 delims=/: " %%J IN ("%%~tV") DO (
SETLOCAL ENABLEDELAYEDEXPANSION
SET oldfile=%%V
SET newfile1=GR%%L%%J%%K%%M%%N-
SET newfile2=!oldfile:~-8!
SET newfile=!newfile1!!newfile2!
ECHO Current filename is "!oldfile!"
ECHO New filename will be "!newfile!"
IF EXIST !newfile! (
ECHO Cannot rename !oldfile!
) ELSE (
ECHO Renaming "!oldfile!" to "!newfile!"
RENAME !oldfile! !newfile!
)
SET newfile=
SET newfile1=
SET newfile2=
SET oldfile=
)
ENDLOCAL
)
ENDLOCAL

If you want, you can use only the first SETLOCAL command and end your FOR /F loop sooner, thus getting rid of one SETLOCAL
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%V IN (D:\test\*.jpg) DO (
SET oldfile=%%V
FOR /F "tokens=1-5 delims=/: " %%J IN ("%%~tV") DO (
SET newfile1=GR%%L%%J%%K%%M%%N-
)
SET newfile2=!oldfile:~-8!
SET newfile=!newfile1!!newfile2!
ECHO Current filename is "!oldfile!"
ECHO New filename will be "!newfile!"
IF EXIST !newfile! (
ECHO Cannot rename !oldfile!
) ELSE (
ECHO Renaming "!oldfile!" to "!newfile!"
RENAME !oldfile! !newfile!
)
SET newfile=
SET newfile1=
SET newfile2=
SET oldfile=
)
ENDLOCAL


Or, if you don't like the extra variables:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
FOR %%V IN (D:\test\*.jpg) DO (
SET newfile=%%V
FOR /F "tokens=1-5 delims=/: " %%J IN ("%%~tV") DO (
SET newfile=GR%%L%%J%%K%%M%%N-!newfile:~-8!
)
ECHO Current filename is "%%V"
ECHO New filename will be "!newfile!"
IF EXIST !newfile! (
ECHO Cannot rename %%V
) ELSE (
ECHO Renaming "%%V" to "!newfile!"
RENAME %%V !newfile!
)
SET newfile=
)
ENDLOCAL


I edited it to change the reference back to D:, I was using C:.