C.W.K.
Stream
Lesson 10 of 12 · published

find — Searching the Filesystem

~15 min · find, search, exec

Level 0Window Tourist
0 XP0/95 lessons0/14 achievements
0/100 XP to next level100 XP to go0% complete

The Swiss Army knife of file search

find walks a directory tree applying tests and actions to every entry. Once you internalize the syntax, you can answer almost any "where is the file that..." question.

The shape

find <path> <tests> <action>. Path defaults to . if omitted (BSD requires it explicitly; macOS works either way in practice). Tests filter; the default action is -print.

The tests you'll use most

  • -name 'pattern' — glob match the basename. Quote it!
  • -iname 'pattern' — case-insensitive.
  • -type f — regular files. Also: d dir, l symlink.
  • -size +10M — bigger than 10 MB. -1k, +500c (chars).
  • -mtime -7 — modified in the last 7 days. -mmin -60 for minutes.
  • -empty — empty files or dirs.
  • -maxdepth 2 — don't recurse deeper. Put it before other tests for performance.

Actions

  • -print — default. Print path.
  • -delete — delete the match. Test with -print first!
  • -exec cmd {} \; — run cmd once per match.
  • -exec cmd {} + — batch matches into one cmd invocation. Like xargs but built in.

Real one-liners

  • Find every Python file under home: find ~ -name '*.py'
  • Files bigger than 100 MB: find / -type f -size +100M 2>/dev/null
  • Old logs to delete: find /var/log -name '*.log' -mtime +30 -delete
  • Pass to grep: find . -name '*.go' -exec grep -l TODO {} +

For interactive search, the fd tool from the modern-tools track is faster and friendlier — but find is on every Unix box.

Code

Triage big files in home·bash
find ~ -type f -size +100M 2>/dev/null -exec ls -lh {} +
# Or sort by size after
find ~ -type f -size +100M 2>/dev/null -exec du -h {} + | sort -h
Find then act — safely·bash
# 1. Print to verify
find /var/log -name '*.gz' -mtime +30 -print
# 2. Confirmed? Then delete.
find /var/log -name '*.gz' -mtime +30 -delete

External links

Exercise

Find every file in your home modified in the last hour: find ~ -type f -mmin -60. Find every Python file under a project: find ./project -name '*.py' -type f. Then practice the two-step pattern: find ./tmp -name '*.tmp' -print, verify, then ... -delete.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.