Search code examples
for-loopbatch-filecmddir

Renaming files in folder using batch file


I'm trying to rename files with a certain format in a specific folder. I'd doing this by creating a text file with file names and referencing that text file in a looped for statement. When I run the commands line by line in cmd it works fine however when I try to run as a batch file it does not work. The batch file is saved in the folder in which I want the operation done so I'm assuming I don't need to declare the directory. Any help would be much appreciated!

dir > file.txt
for /f "tokens=1,2,3,4 delims=_." %i in (file.txt) do ren "%i_%j_%k.%l" "%date:~10%%date:~4,2%%date:~7,2%_%time:~0,2%h%time:~3,2%m%time:~6,2%s_%k.%l"

:END

Solution

  • When writing for loops in cmd scripts the for variables (ex: %i) needs to be escaped with a extra % so it becomes:

    for /f "tokens=1,2,3,4 delims=_." %%i in (file.txt) do ren "%%i_%%j_%%k.%%l" "%date:~10%%date:~4,2%%date:~7,2%_%time:~0,2%h%time:~3,2%m%time:~6,2%s_%%k.%%l"
    

    To read more how for works type for /? in cmd.

    The interesting part:

    To use the FOR command in a batch program, specify %%variable instead of %variable. Variable names are case sensitive, so %i is different from %I.