Search code examples
windowsbatch-filecmdcommand-prompt

Need help replacing specific parts of multiple directory names


I want to use cmd.exe or a batch file to replace a specific string in all directories within one location.

e.g. directory 1900abcd - 1900wxyz becomes 1700abcd - 1700wxyz.

The abcd and wxyz parts of the directory names must stay the same.

I've done lots of looking around, and only seen ways to trim directory names, not replacing characters at specific positions within the name. I have tried structuring a For loop for this, but I don't fully understand how to adapt it for this purpose.

Update: some outside input leaves me with this as a working possibility, maybe some help getting this batch file format to work?

setlocal enabledelayedexpansion

set "oldsubstring=old"
set "newsubstring=new"

for /d %%D in (*) do (
   set "folder name=%%D"
   set "newfoldername=!folder name:%oldsubstring%=%newsubstring%!"
   ren "%%D""!newfoldername!"
)

endlocal

Solution

  • Yay! The solution! All credit to my brother for this code, where old is the string within the folder name you want replacing, and new is what it will become. It will change all instances of this string within the name. Saved as a batch file, this will work for every folder in the parent folder they're in.

    @echo off
    setlocal enabledelayedexpansion
    
    set "oldsubstring=old"
    set "newsubstring=new"
    
    for /d %%F in (*) do (
         set "foldername=%%F"
         set "newname=!foldername:%oldsubstring%=%newsubstring%!"
         ren "%%F" "!newname!"
    )
    
    endlocal