Logo

How can I recursively find all files in current and subfolders based on wildcard matching?

1. Using the find Command
The most universal way—working in Bash, Zsh, and most other shells—is to use find. For instance, to locate all *.txt files (case-sensitive) in the current folder and its subfolders:

find . -type f -name "*.txt"
  • .: Search in the current directory (including subdirectories).
  • -type f: Restrict results to regular files only.
  • -name "*.txt": Match files ending with .txt.

If you want a case-insensitive match (e.g., matching .TXT or .Txt as well):

find . -type f -iname "*.txt"

If you need to match multiple patterns, group them with parentheses and -o (logical OR):

find . -type f \( -name "*.txt" -o -name "*.md" \)

2. Using Zsh Globs
If you’re using Zsh, you can leverage its “recursive glob” feature:

ls **/*.txt
  • **/*.txt: Recursively matches all .txt files from the current directory downward.

(If ls **/*.txt doesn’t work, ensure your Zsh configuration enables extended_glob or globstar.)

3. Additional Find Options

  • Exclude directories:

    find . -type d -name "node_modules" -prune -o -type f -name "*.js" -print

    This skips node_modules and searches for *.js in all other directories.

  • Execute commands on found files (e.g., removing them):

    find . -type f -name "*.bak" -exec rm {} \;

Use whichever approach best fits your shell environment. In most cases, find is the go-to solution for reliable, portable, and flexible file searches.

CONTRIBUTOR
TechGrind