Search code examples
batch-filebatch-processingbatch-rename

How to add recursive directory to batch file


I have the following batch file:

@echo off
for /f "delims=" %%F in (
  'dir /b /a-d [*]*'
) do for /f "tokens=1* delims=]" %%A in (
  "%%F"
) do for /f "tokens=*" %%C in ("%%B") do ren "%%F" "%%C"

I want launch it in the root directory and have it go through all directories and subdirectories performing the actions.

I tried adding /D and /r to the 'for' lines, but it doesn't appear to be working.

Do I need add something like...

for /D /r do

under the @echo off ?


Solution

  • Use either dir or for to get all the files, don't mix it up. When using dir /S for recursive enumeration, regard that full paths are output rather than pure file names only. This should do it:

    @echo off
    for /f "delims=" %%F in (
      'dir /s /b /a-d [*]*'
    ) do for /f "tokens=2* delims=]" %%B in (
      "%%~nxF"
    ) do for /f "tokens=*" %%C in ("%%B") do ren "%%~F" "%%C"
    

    So I just changed the following in your original code:

    • added /s to dir (returns full paths then);
    • improved second for options (you never used the first token %%A, so why extract it then?);
    • replaced set %%F of second for by %%~nxF to just parse the file name (type for /? for details concerning substitution modifiers such as ~n, ~x);
    • replaced source argument "%%F" of ren command by "%%~F" to not fall into double-double-quote problems (the ~ modifier removes potential double-quotes);