Find files

3 snippets across 2 stacks - Bash & Linux, Python

Also written as file search · search files · find in files

SHBash & Linux

Find Files by Criteria

SH · Navigation & Files
Syntax
find [path] [expression]
Example
find /var/log -name '*.log' -mtime -7
find . -type f -size +100M
find src/ -name '*.ts' -exec wc -l {} +
Output
/var/log/syslog
/var/log/auth.log

Note -name is case-sensitive; use -iname for case-insensitive. -mtime -7 means modified in the last 7 days. -exec runs a command on each result; use + instead of \; to batch them for better performance.

Search Text with Patterns

SH · Text Processing
Syntax
grep [options] pattern [file...]
Example
grep -rn 'TODO' src/
grep -i 'error' /var/log/syslog
grep -c 'SELECT' queries.sql
grep -v '^#' nginx.conf
Output
src/api/handler.go:42:  // TODO: add rate limiting
src/lib/cache.ts:18:  // TODO: implement TTL

Note -r searches recursively through directories. -n shows line numbers. -i is case-insensitive. -v inverts the match (shows non-matching lines). -c counts matches. -l lists only filenames with matches. Use -E for extended regex or egrep.

PYPython

Finding Files with Glob

PY · File I/O
Syntax
Path(dir).glob(pattern)
Path(dir).rglob(pattern)
Example
from pathlib import Path

# All Python files in current directory
for py_file in Path(".").glob("*.py"):
    print(py_file.name)

# Recursive search
all_json = list(Path(".").rglob("*.json"))
print(f"Found {len(all_json)} JSON files")

Note glob() searches one level. rglob() searches recursively through all subdirectories. Both return Path objects.

Frequently asked questions

How do you find files?
This task is covered in 2 stacks on this page: Bash & Linux, Python. The "Find Files by Criteria" snippet in Bash & Linux uses `find [path] [expression]`.
Which command does the Bash & Linux example use?
The "Find Files by Criteria" snippet uses `find [path] [expression]`, from the Navigation & Files section of the Bash & Linux cheat sheet.
Which stacks cover "find files" on this page?
Bash & Linux, Python. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Find Files by Criteria": -name is case-sensitive; use -iname for case-insensitive. -mtime -7 means modified in the last 7 days. -exec runs a command on each result; use + instead of \; to batch them for better performance.