Search code examples
batch-filefor-loopcommand-linecommand-promptdir

Loop through files in subdirectories batch file


I am trying to loop through a bunch of files in sub-directories to run a command on them, but I can't seem to figure out how to reach them.

The directory structure is like this:

  • Main directory (Holds .bat file and top-level directories)
    • Sub-directory
      • Search directory
        • A bunch of files (I need the locations of all of these separately)

I am able to get a list of all of the files/folders in the "Main directory" using:

for /f %%f in ('dir /b /r *') do echo %%f

but I cannot seem to figure out how to go any further into the directories to get the files in the "Search" directory.

An example of the file structure is:

C:\Users\swiftsly\Search160\0002\search\AP584.txt

Any help is greatly appreciated!


Solution

  • The final solution to this question, with the help of the recommendation by Squashman to use /R instead of /f is:

    @echo off    
    for /R %%f in (*.txt) do echo %%f
    

    This will print out a list of all of the .txt files in the sub-directories.