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.