Windows Command Prompt – How to Rename a Set of Files

command linerenamewindows

How to rename a set of files like this in the Windows command prompt?

current file names:

file111.txt  
file112.txt  
file113.txt  

after renaming file names:

file0111.txt  
file0112.txt  
file0113.txt  

How can I achieve this?

Best Answer

Batch script:

for %%f in (file???.txt) do call :ren %%f
goto :eof

:ren
    set name=%1
    ren "%name%" "%name:~0,4%0%name:~4%"

    :: Here, %name:~0,4% takes the first four characters, then you add a "0",
    :: and %name:~4% is everything after the fourth character.

Another possible way, which checks for all files starting with file100.txt and so on, so might be slower:

for /l %f in (100,1,999) do if exist "file%f.txt" ren "file%f.txt" "file0%f.txt"

(If you want to put this in a batch file, you need to change %f to %%f, same as in the first example.)

Related Question