Search code examples
batch-filefor-looprecursionsubdirectory

Run command (or batch file) in every subfolder


I want to run a script (which I have in a .bat file already)

"c:\Flac\flac.exe" -8 *.wav --verify --delete-input-file --replay-gain

in all subfolders of a main folder.

If I take this .bat file and copy/paste it into any folder and run it, it works great and I get the expected results. However, if I have a main folder with 50 folders that I want to do this in, it takes forever to copy and paste that file 50 times.

Been trying to figure out the syntax for using (I assume) the command FOR /R but can't seem to get it right.

For example let's say directory tree is this:

c:\
     FLAC
          flac.exe
          flac BATCH.bat
     Music to be converted
          1
          2
          3

I want to run the C:\FLAC\flac BATCH.bat in every subfolder of C:\Music to be converted

I've tried

FOR /R "C:\Music to be converted" %X IN (*.wav) DO "C:\FLAC\flac BATCH.bat" "%X"

but this doesn't work. I need the FOR /R command to go through the subfolders, don't I?


Solution

  • Based on my comment.

    From the command line:

    For /D %A In ("C:\Music to be converted\*") Do @(PushD "%~A" & "C:\Flac\flac.exe" -8 *.wav --verify --delete-input-file --replay-gain & PopD)
    

    Or as a batch file:

    @Echo Off
    For /D %%A In ("C:\Music to be converted\*") Do (PushD "%%~A"
        "C:\Flac\flac.exe" -8 *.wav --verify --delete-input-file --replay-gain
        PopD)