Skip to main content

How to Use the FOR /R Loop: Recursively Search for Files in Batch Script

A common and powerful scripting task is to perform an action on every file of a certain type, not just in a single directory, but across an entire directory tree. You might need to find all .log files to archive them, or delete all .tmp files from a user's profile. Manually navigating into every subfolder is impossible, which is why the FOR /R loop is an essential tool.

This guide will teach you how to use the FOR /R loop to recursively walk through a directory structure and find files that match a specific pattern. You will learn how to set a starting point for your search and see a practical example of a script that finds and reports on all MP3 files in a music library.

A recursive search is one that "walks a directory tree." It starts in a specified folder, processes the files there, and then it goes into every subdirectory, processing the files inside them, and then it goes into their subdirectories, and so on, until every folder and file in the entire hierarchy has been visited. The FOR /R loop is the built-in batch command for performing this kind of search.

The Core Command: FOR /R

The FOR /R loop iterates through files in a directory and all of its subdirectories, matching a specified file pattern.

The syntax is: FOR /R [path] %%F IN (file_pattern) DO (command)

  • /R: Specifies a Recursive loop.
  • [path]: An optional starting directory. If omitted, the search starts in the current directory.
  • %%F: The loop variable that will hold the full path of each matching file found.
  • (file_pattern): The file(s) to search for, typically using a wildcard. Example: (*.txt), (image_*.jpg).

Basic Example: Finding All Text Files

This script, when run, will find every single .txt file in the current directory and all folders below it.

@ECHO OFF
ECHO --- Recursively finding all .txt files ---
ECHO Starting from the current directory: %CD%
ECHO.

FOR /R %%F IN (*.txt) DO (
ECHO Found file: "%%F"
)

ECHO.
ECHO --- Search complete ---

In the Output (if run from a user's Documents folder), the loop variable %%F always contains the full, absolute path to the file.

--- Recursively finding all .txt files ---
Starting from the current directory: C:\Users\Admin\Documents

Found file: "C:\Users\Admin\Documents\notes.txt"
Found file: "C:\Users\Admin\Documents\ProjectA\readme.txt"
Found file: "C:\Users\Admin\Documents\ProjectA\src\config.txt"
Found file: "C:\Users\Admin\Documents\Archive\old_notes.txt"

--- Search complete ---

How FOR /R Works

The command FOR /R %%F IN (*.txt) instructs the command processor to perform the following steps:

  1. Start in the current directory.
  2. Does this directory contain any .txt files? If so, run the DO block for each one, with %%F holding the full path.
  3. Does this directory contain any subdirectories?
  4. If yes, for each subdirectory, "descend" into it and go back to step 2.
  5. Continue until all directories in the entire tree have been visited.

Specifying a Starting Directory

Most of the time, you don't want to search from the current directory. You can specify an explicit starting point right after the /R.

This script specifically targets a user's Downloads folder, regardless of where the script itself is run from.

@ECHO OFF
ECHO --- Finding all .tmp files in the Downloads folder ---
ECHO.

FOR /R "%USERPROFILE%\Downloads" %%T IN (*.tmp) DO (
ECHO Found temporary file: "%%T"
)

ECHO.
ECHO --- Search complete ---

Common Pitfalls and How to Solve Them

Problem: The Path Contains Spaces

If your starting path contains spaces, you must enclose it in double quotes.

Example of script with error:

REM This will FAIL.
FOR /R C:\My Project Files %%F IN (*.log) DO ECHO %%F

Solution: Always Quote Your Paths

This is a universal best practice that prevents path-related errors.

REM This is the correct, safe syntax.
FOR /R "C:\My Project Files" %%F IN (*.log) DO ECHO %%F

Problem: Needing Just the Filename, Not the Full Path

The %%F variable always contains the full path, but sometimes you only want the filename and extension, or just the parent folder.

Solution: Use Tilde Modifiers

The FOR command provides special "tilde modifiers" to deconstruct the path.

  • %%~nxF: Expands to the name and extension only.
  • %%~dpF: Expands to the drive and path only.
  • %%~zF: Expands to the file's size.
@ECHO OFF
FOR /R "C:\MyProject" %%F IN (*.js) DO (
ECHO Full Path: %%F
ECHO File Name: %%~nxF
ECHO Parent Dir: %%~dpF
ECHO Size (bytes): %%~zF
ECHO.
)

Practical Example: A Music File Scanner

This script recursively scans a Music library folder, finds all .mp3 files, and generates a simple report of their full paths and file sizes.

@ECHO OFF
SETLOCAL
SET "MUSIC_LIBRARY=%USERPROFILE%\Music"
SET "REPORT_FILE=%USERPROFILE%\Desktop\Music_Report.txt"

ECHO --- Music Library Scanner --- > "%REPORT_FILE%"
ECHO Scan started on %DATE% at %TIME% >> "%REPORT_FILE%"
ECHO ==================================== >> "%REPORT_FILE%"
ECHO.

ECHO Scanning "%MUSIC_LIBRARY%" for all .mp3 files...

REM Use >> to append each found file to our report.
FOR /R "%MUSIC_LIBRARY%" %%M IN (*.mp3) DO (
ECHO [%%~zM bytes] - %%M >> "%REPORT_FILE%"
)

ECHO.
ECHO [SUCCESS] Scan complete. Report saved to Desktop.
START "" "%REPORT_FILE%"
ENDLOCAL

Conclusion

The FOR /R loop is the essential tool for performing recursive file operations in a batch script. It provides a simple and powerful way to walk an entire directory tree and act on every file that matches a pattern.

Key takeaways for using FOR /R:

  • Use FOR /R to start a recursive search from the current directory.
  • Use FOR /R "path" to specify an explicit starting directory.
  • Use a wildcard pattern like *.txt in the IN() clause to define what you're looking for.
  • Remember that the loop variable (%%F) contains the full path of the file.
  • Use tilde modifiers (%%~nxF, %%~dpF, %%~zF) to extract different parts of the file's information.