5. Find, Xargs, and the Art of File Discovery
Locate files by any attribute and act on them at scale
ls shows you what's in a directory. find searches an entire directory tree
using any combination of criteria — name, type, size, modification time,
permissions, ownership — and lets you act on the results. Paired with xargs,
it becomes a general-purpose engine for running commands on thousands of files
efficiently.
These two tools together solve a problem that comes up constantly: "find all the files that match some condition and do something with each one."
Find Basics
The simplest find command searches a directory tree for files matching a name:
find /var/log -name "*.log"
This walks every directory under /var/log and prints each file whose name
matches the glob *.log.
The general form is:
find [starting-path...] [expression]
If you omit the starting path, find uses the current directory.
Find all Python files in the current tree
find . -name "*.py"
Case-insensitive matching
find . -iname "readme*" # matches README.md, readme.txt, ReadMe, etc.
Filtering by Type
The -type predicate restricts results to specific kinds of filesystem entries:
| Flag | Type |
|---|---|
f |
Regular file |
d |
Directory |
l |
Symbolic link |
p |
Named pipe (FIFO) |
s |
Socket |
Find only directories
find /etc -type d -name "*.d"
Filtering by Time
find can filter by when files were last modified, accessed, or had their
metadata changed:
| Predicate | Meaning |
|---|---|
-mtime -7 |
Modified in the last 7 days |
-mtime +30 |
Modified more than 30 days ago |
-mtime 0 |
Modified today (within last 24 hours) |
-mmin -60 |
Modified in the last 60 minutes |
-newer ref |
Modified more recently than file ref |
The +/- convention applies everywhere in find: + means "more than,"
- means "less than," and a bare number means "exactly."
Find files modified in the last hour
find /var/log -name "*.log" -mmin -60
Find stale files
# Files not modified in over 90 days
find /tmp -type f -mtime +90
Filtering by Size
| Predicate | Meaning |
|---|---|
-size +100M |
Larger than 100 MB |
-size -1k |
Smaller than 1 KB |
-size 0 |
Empty files |
-empty |
Empty files or directories |
Suffixes: c (bytes), k (kilobytes), M (megabytes), G (gigabytes).
Find large log files
find /var/log -name "*.log" -size +50M
Combining Predicates
By default, multiple predicates are ANDed together. You can also use explicit boolean logic:
| Operator | Meaning |
|---|---|
| (implicit) | AND — both must match |
-o |
OR — either must match |
! or -not |
Negate the next predicate |
\( ... \) |
Group expressions |
Find images (multiple extensions)
find . -type f \( -name "*.jpg" -o -name "*.png" -o -name "*.gif" \)
Exclude a directory
find . -path ./node_modules -prune -o -name "*.js" -print
-prune tells find not to descend into the matched directory.
Depth Control
| Option | Effect |
|---|---|
-maxdepth N |
Don't descend more than N levels |
-mindepth N |
Ignore results shallower than N levels |
# Only look in the immediate directory, not subdirectories
find . -maxdepth 1 -name "*.txt"
Acting on Results: -exec
find can execute a command on each result using -exec:
find . -name "*.tmp" -exec rm {} \;
{}is replaced with the current filename\;marks the end of the command (one execution per file)
Change permissions on all shell scripts
find . -name "*.sh" -exec chmod +x {} \;
Batch mode with +
Replace \; with + to pass as many files as possible to a single command
invocation (like xargs):
find . -name "*.js" -exec grep -l "TODO" {} +
This is faster than \; because it avoids spawning a new process for each file.
Confirmation with -ok
-ok works like -exec but prompts for confirmation before each command:
find /tmp -mtime +30 -ok rm {} \;
# < rm ... /tmp/old_file.txt > ? y
Xargs — The Pipeline Bridge
xargs reads items from stdin and runs a command with those items as
arguments. It's how you connect find (or any command that produces a list)
to tools that expect arguments, not stdin.
find . -name "*.log" | xargs wc -l
Without xargs, wc would try to read log data from stdin. With xargs,
each filename becomes a command-line argument to wc.
How xargs batches
By default, xargs collects as many arguments as will fit on a single
command line (typically 128–256 KB) and runs one command. If there are too
many arguments, it runs the command multiple times.
# Equivalent to: grep -l "error" file1.log file2.log ... (as many as fit)
find . -name "*.log" | xargs grep -l "error"
Limiting batch size with -n
# Run diff with exactly 2 files at a time
find . -name "*.bak" | xargs -n 2 diff
The Filename Problem
Filenames can contain spaces, quotes, and even newlines. A plain find | xargs
pipeline breaks on these because xargs splits on whitespace by default.
The fix: null-delimited mode.
find . -name "*.txt" -print0 | xargs -0 rm
-print0makesfindseparate results with null bytes (\0) instead of newlines-0makesxargssplit on null bytes
This is bulletproof for any filename. Always use -print0 and -0 when
processing files that might have unusual names.
Placeholder with -I
Use -I to control where arguments are placed:
find . -name "*.conf" | xargs -I{} cp {} /backup/{}
-I also implies -n 1 (one argument per execution).
Parallel execution with -P
xargs can run commands in parallel:
find . -name "*.png" -print0 | xargs -0 -P 4 -I{} convert {} -resize 50% {}
-P 4 runs up to 4 processes simultaneously. For CPU-bound tasks on
multi-core machines, this is a simple way to get significant speedups.
Find + Xargs Patterns
Search file contents
find . -name "*.py" -print0 | xargs -0 grep -n "import os"
Bulk rename
# Rename .txt to .md
find . -name "*.txt" -print0 | xargs -0 -I{} bash -c 'mv "$1" "${1%.txt}.md"' _ {}
Delete old files safely
# Show what would be deleted first
find /tmp -type f -mtime +30 -print
# Then delete
find /tmp -type f -mtime +30 -print0 | xargs -0 rm -v
Count lines across a codebase
find src/ -name "*.ts" -print0 | xargs -0 wc -l | tail -1
Archive matching files
find . -name "*.log" -mtime +7 -print0 | xargs -0 tar czf old-logs.tar.gz
Find Alternatives
find is universal but verbose. Newer tools optimize for common cases:
| Tool | Strength |
|---|---|
fd |
Simpler syntax, ignores .gitignore, colorized output |
locate |
Instant lookup from a pre-built database (run updatedb first) |
tree |
Visual directory tree (not a search tool, but useful for overview) |
fd in particular has become popular for interactive use:
# fd equivalent of: find . -name "*.py" -type f
fd -e py
But find remains the standard — it's on every Unix system, it's POSIX, and
scripts that use it work everywhere.
Common Pitfalls
Forgetting -print0 / -0
# Breaks on "my file.txt"
find . -name "*.txt" | xargs rm
# Safe
find . -name "*.txt" -print0 | xargs -0 rm
-exec + vs. xargs
find -exec {} + and find | xargs do similar things. Key differences:
-exec +doesn't need-print0— it handles filenames correctly by defaultxargsoffers-Pfor parallelism and-Ifor placement controlxargscan be fed from any source, not justfind
Symbolic link behavior
By default, find does not follow symbolic links. Use -L to follow them:
find -L /opt -name "*.so"
Summary
findwalks directory trees matching files by name, type, size, time, and permissions- Predicates combine with implicit AND, explicit
-o(OR), and!(NOT) -exec {} \;runs a command per file;-exec {} +batches them-pruneskips directories;-maxdepthlimits recursionxargsturns stdin lines into command arguments, with batching and parallelism (-P)- Always use
-print0/-0for safe handling of filenames with spaces - Together,
findandxargsare the general-purpose engine for "find files, then act on them"