grep and find: A Practical Guide
Search file contents with grep and the filesystem with find. Learn the flags that matter and how to combine them safely.
By Velloreth
grep: searching contents
The basic form is grep pattern file.
grep "TODO" src/main.js
Recursive searches a directory tree.
grep -r "TODO" src/
The flags that matter:
| Flag | Meaning |
|---|---|
-i | case-insensitive |
-n | show the line number |
-r | recursive |
-l | list only the file names |
-c | count the matches |
-v | invert, show the non-matching lines |
-w | match a whole word |
-F | treat the pattern as a fixed string |
-E | extended regular expressions |
-A n | show n lines after a match |
-B n | show n lines before a match |
-C n | show n lines of context |
-l is often what you want. A search for a symbol usually ends with “which files use this”, not “show me every line”.
grep -rl "deprecatedFunction" src/
Context is what makes a match readable.
grep -rn -C 3 "throw new Error" src/
Limiting a grep
A recursive grep on a project directory searches node_modules and .git, which is slow and noisy.
grep -r "TODO" . \
--exclude-dir=node_modules \
--exclude-dir=.git \
--exclude-dir=dist \
--include="*.ts" \
--include="*.tsx"
--include limits the file types, and --exclude-dir skips a directory. Both are faster than searching and filtering.
-I skips binary files, which avoids a screen of binary output.
grep -rI "config" /etc
-m stops after a number of matches per file, which is useful for a quick check.
grep -rm 1 "version" package.json
Regular expressions
Basic treats +, ?, |, ( and ) as literals.
grep "a+b" file # matches the literal a+b
Extended treats them as operators.
grep -E "a+b" file # matches one or more a
grep -E "^(foo|bar)" file
-F is the fixed-string mode, which is faster and avoids escaping.
grep -F "a+b" file
A pattern that starts with a dash needs -- to end the options.
grep -- "-v" file
find: searching the filesystem
The basic form is find path criteria action.
find . -name "*.log"
find /var -type f -size +100M
find . -type d -name node_modules
The criteria that matter:
| Criterion | Meaning |
|---|---|
-name | match the file name (case-sensitive) |
-iname | match the file name (case-insensitive) |
-type f | a regular file |
-type d | a directory |
-size +10M | larger than 10 MB |
-mtime -7 | modified in the last 7 days |
-mmin -60 | modified in the last 60 minutes |
-user alice | owned by alice |
-perm 644 | with this exact mode |
-empty | empty |
Combine with -and, -or and !.
find . -type f -name "*.log" -mtime +30
find . -type f \( -name "*.js" -o -name "*.ts" \) -size +1M
find . -type f ! -name "*.md"
-maxdepth limits the recursion, which is a large speedup.
find . -maxdepth 2 -name "*.json"
Acting on the results
-exec runs a command per file.
find . -name "*.tmp" -exec rm {} \;
{} is the file, and \; ends the command. The + form batches several files into one invocation, which is faster.
find . -name "*.log" -exec gzip {} +
-delete removes the matches, and it is faster than -exec rm.
find . -name "*.tmp" -delete
The caution: -delete acts on whatever the criteria match. Run the same find without -delete first to see the list.
-print0 and xargs -0 handle a filename with a space.
find . -name "*.log" -print0 | xargs -0 gzip
A plain xargs splits on whitespace, so a filename with a space becomes two arguments. The null-delimited form is the safe one.
Combining find and grep
The pattern that is worth remembering: find selects the files, grep searches inside them.
find src -type f -name "*.ts" -exec grep -l "TODO" {} +
Or with xargs.
find src -type f -name "*.ts" -print0 | xargs -0 grep -l "TODO"
grep -r is simpler for the common case, and the find-and-grep combination is for when the file selection is more complex than a directory and an extension.
Why the shell tools still matter
A graphical tool is faster for a one-off search, and the shell tools are faster for a search that has to be repeated, scripted, or run on a server. The reason is composition: grep and find read from a pipe and write to one, so they combine with each other and with any other tool. A search that starts as an interactive command becomes a script by adding a loop, and the same script runs in a CI job without a change. The second reason is that the tools are present everywhere. A container image, a build server, and a minimal server install all have grep and find, and a tool that must be installed is a tool that is not available when it is needed most. The third reason is precision: a regular expression and a set of criteria express a search that a graphical tool cannot, and the result is reproducible.
A search strategy
A search is most effective when it narrows in stages rather than starting with the most specific pattern. The first stage is to find the files, which is a find with a name, a type and a directory limit. The second is to search inside them, which is a grep with a fixed string and a file list. The third is to narrow the result, which is a grep with a line number and a context, or a pipe to a second filter. The fourth is to confirm the match, which is to open the file at the line the search reported. The reason to work in stages is that a broad search is fast and a narrow one is slow, and a search that starts narrow often misses the file because the assumption about the name or the directory was wrong. A search that starts broad and narrows finds the answer even when the first assumption is incorrect, which is the common case in an unfamiliar codebase.
Common mistakes
A recursive grep without exclusions. It searches node_modules and .git, which is slow and noisy.
Piping find to a plain xargs. A filename with a space is split. Use -print0 and xargs -0.
find -delete without checking the criteria first. It removes whatever matches. Run the find without the action first.
A pattern with an unescaped special character. Use -F for a literal, or escape the character.
grep on a binary file. The output is unreadable. Use -I to skip binaries, or -a to treat them as text.
find on / without a limit. It traverses the whole filesystem, including the virtual filesystems. Limit the path and the depth.
Assuming -name is case-insensitive. It is not. Use -iname.
A quotable summary
grep searches file contents and find searches the filesystem, and the two are often combined: find selects the files and grep searches inside them. Use grep -r with --include and --exclude-dir to keep a recursive search fast, and -l when you want the file names rather than the lines. Use find with -name, -type, -size and -mtime to select files, and prefer -print0 with xargs -0 over a plain pipe so a filename with a space is handled correctly.
Related reading
For the shell around this, see linux-command-line-basics and for the JSON tool, jq-json-command-line. For the broader context, bash-scripting-basics and linux-file-permissions.