Search code examples
batch-filecommand

how to rename multiple sub directories of a parent folder with a script?


I have parent folder with several sub directories which contain folders named the same to be renamed to the same name. I would like place a script at the parent folder that will traverse through the subfolders and rename directories according to a match. For instance in each folder with a folder name Foo rename it to Apple.

the script I have not working is

FOR /D %%D IN (*.*) DO (
    REN "Foo"   "Apple"
    REN "Bar" "Banana"
    REN "Baz"  "Mango"
)

inside the for loop that script is trying to rename files. If I place the lines below in a .cmd file it will rename folders

REN "Foo" "Apple"

I would like to place the script in the parent folder and have it search through the sub folders and rename all the Foo folders to Apple, all the Bar folders to Banana, and all the Baz folders to Mango

Current Folder Tree:

|  Parent Folder
|  |--Sub Folder 1
|  |  |--Foo
|  |  |--Bar
|  |  |--Baz
|  |--Sub Folder 2
|  |  |--Foo
|  |  |--Bar
|  |  |--Baz
|  |--Sub Folder 3
|  |  |--Foo
|  |  |--Bar
|  |  |--Baz

Renamed Folder Tree would be:

|  Parent Folder
|  |--Sub Folder 1
|  |  |--Apple
|  |  |--Banana
|  |  |--Mango
|  |--Sub Folder 2
|  |  |--Apple
|  |  |--Banana
|  |  |--Mango
|  |--Sub Folder 3
|  |  |--Apple
|  |  |--Banana
|  |  |--Mango

Thanks for any help!


Solution

  • [untested]

    for /d /r %%e in (*.*) do (
     echo ren "%%e\Foo" "Apple" 2>nul
     echo ren "%%e\Bar" "Banana" 2>nul
     ...
    )
    

    The ren commands are echoed to the console for verification purposes.

    If the resultant list is what you want to do, remove the echo keywords to activate the rename.

    The 2>nul should suppress error messages (like if Foo does not exist)