grep Cheatsheet
Top patterns.
Overview
grep is the line-matching tool that anchors Unix text search. Five primitive surfaces cover almost every operational use: regex pattern matching, recursive directory traversal, surrounding context, inverted matches, and word/line anchors for precision. rg (ripgrep) and ag (the silver searcher) are faster modern alternatives on large trees; the BSD/GNU grep on every Unix box covers everywhere else.
- Pattern matching. Lines matching a regex. The filter that turns logs into investigation data.
- Recursive search.
-rwalks directory trees. Finds occurrences across an entire codebase. - Context flags.
-A,-B,-Cshow surrounding lines. Matches become understandable in context. - Inverted match plus anchors.
-vfor exclusion patterns;-wfor whole word,-xfor whole line.
The approach
Five idioms cover almost every operational use of grep. Memorising them moves the team from copy-pasted commands to confident text investigation.
grep -i pattern. Case-insensitive search. Catches the mixed-case log lines that exact-match misses.grep -r --include="*.py" pattern. Recursive with file glob. Limits search scope to relevant files.grep -A 5 pattern. Five lines of trailing context. Stack traces and surrounding log lines become readable.grep -E "p1|p2"plusrg. Extended regex with alternation;rgoragon large trees for speed.
Why this compounds
Each grep one-liner replaces a manual scroll through a log file. The team’s text-search fluency deepens; regex skills transfer to sed, awk, log queries, and code-aware tooling.
- Faster investigation. One-liners replace full-file scrolling. Root cause arrives faster.
- Composable filters.
grepin pipelines produces precise multi-stage filtering. - Universal availability. Present on every Unix box. No installation, no dependency.
- Year-one investment, year-two habit. First year builds fluency. By year two,
grepis the default for any text-search problem.