How to Enable Subdirectory Recursion in 7-Zip CLI

This guide explains how to enable and control directory recursion using the 7-Zip Command Line Interface (CLI). By using the -r switch and its variations, you can search for and process files located across nested folders during compression and extraction tasks. Below, you will find the exact syntax, available switch variations, and practical command examples to handle recursive operations correctly.

The -r Recursion Switch

In the 7-Zip CLI, recursion is controlled using the -r switch. It tells 7-Zip to search for files matching your specified pattern not only in the current working directory but also within all child directories.

The switch has three variations:

  • -r: Enables recursion through all subdirectories for matching file patterns.
  • -r-: Explicitly disables recursion (the default state for most pattern-based commands).
  • -r0: Enables recursion only for wildcard names (e.g., *.txt), ignoring non-wildcard names.

Syntax and Practical Examples

To apply recursion, append the switch to your command along with the archive name and the target file pattern.

1. Archiving Specific File Types Recursively

To archive all files with a .txt extension located in the current directory and all subdirectories:

7z a my_archive.7z -r *.txt

2. Archiving from a Specific Directory Path

To search recursively within a specific folder rather than the current working directory, place the switch alongside the path pattern:

7z a backup.zip -r C:\Projects\*.log

3. Using the -r0 Modifier for Wildcards

To limit recursion strictly to wildcard patterns while keeping specific files restricted to the base directory:

7z a archive.7z -r0 config.json *.xml

In this command, config.json is only checked in the base path, whereas *.xml will search across all subdirectories.

Important Considerations

  • Adding Whole Directories vs. Wildcards: If you want to compress an entire directory and all its contents, you do not need the -r switch. Running 7z a archive.7z MyFolder will automatically include all subfolders and files inside MyFolder. The -r switch is primarily required when using wildcards or filtering by file extensions across subdirectories.
  • Preserving Folder Paths on Extraction: To restore files along with their recursive folder structure, always use the x (extract with full paths) command instead of e (extract flat without paths):
7z x my_archive.7z