Search code examples
windowsbatch-filerecursionfilenamesrename

Recursively rename files in subfolders Windows batch file


I have a large number of files in subfolders under a parent folder called C:\Images.

All files have a prefix pattern of exactly the same length, 3 characters, i.e. "[digit][digit]-"

01-filename.jpg
55-filename.jpg
82-filename.jpg

I have worked out how to strip the prefix from filenames by running a batch file in each subfolder, but I want to run one batch files that will start at the parent folder and recursively step through each subfolder and rename / strip the prefix off each filename.

The code below doesn't work :-( any help would be great :-)

setlocal enabledelayedexpansion
for /r "c:\images\" %%f in (*.jpg) do (
pushd 
set filename=%%f
set filename=!filename:~3!
rename "%%f" "!filename!"
popd
)

Solution

  • You should pass the filename that doesn't include the path on the second argument to rename:

    @echo off
    setlocal enabledelayedexpansion
    for /r "c:\images\" %%f in (*.jpg) do (
        set filename=%%~nxf
        set filename=!filename:~3!
        rename "%%f" "!filename!"
    )
    

    %%~nxI gives both filename and extension.

    It may also be a very good idea to check if the file is really needed to be renamed:

    @echo off
    setlocal enabledelayedexpansion
    for /r "c:\images\" %%f in (*.jpg) do (
        set filename=%%~nxf
        if "!filename:~2,1!" == "-" (
            set filename=!filename:~3!
            rename "%%f" "!filename!"
        )
    )
    

    Finally consider adding a message:

    @echo off
    setlocal enabledelayedexpansion
    for /r "c:\images\" %%f in (*.jpg) do (
        set filename=%%~nxf
        if "!filename:~2,1!" == "-" (
            set filename=!filename:~3!
            echo Renaming %%f to !filename!.
            rename "%%f" "!filename!"
        ) else (
            echo Skipping file %%f.
        )
    )
    

    And you don't need pushd and popd for that.