batch-filedosfile-renamezero-pad

DOS Batch Rename Files


I have a large set files with names structured string_int_int_int_string.extension, and would like to batch rename them with left zero padding to 7 digits on the second int.

Example: rename stringA_1_2_3_stringB.jpg to stringA_1_0000002_3_stringB.jpg.

I've seen some helpful posts here, here, and here but haven't quite done it.

Here is what I have so far (not working, of course):

dir /b *.* >temp.txt

for /f "tokens=%%1,%%2,%%3,%%4,%%5 delims=_" %x in (temp.txt) do (
    setlocal enabledelayedexpansion
    set PAD=000000%%k
    set PAD=!PAD:~7!
    ren "%%i_%%j_%%k_%%l_%%m" %%i_%%j_%PAD%_%%l_%%m
)

I specifically want to do this with a batch file, not some other language or tool. (I'm aware of the various renaming tools out there.)

Any help is most welcome!


Solution

  • setlocal EnableDelayedExpansion
    dir /b *.* >temp.txt
    for /F "tokens=1-5 delims=_" %%a in (temp.txt) do (
       set PAD=000000%%c
       set PAD=!PAD:~-7!
       ren "%%a_%%b_%%c_%%d_%%e"  "%%a_%%b_!PAD!_%%d_%%e"
    )