Loop through files in subdirectories batch file

12,947

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.

Share:
12,947
swiftsly
Author by

swiftsly

Updated on June 04, 2022

Comments

  • swiftsly
    swiftsly almost 2 years

    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!