All cheat sheets

grep Cheat Sheet

grep patterns and flags: literal/regex search, inversion, context, files, and one-liners.

CLI & Shell
grep
search
cli

grep selects lines matching a pattern from files or standard input. Combine a narrow pattern with explicit options, and quote expressions so the shell does not reinterpret regex metacharacters.

Everyday flags

These options cover most interactive searches. GNU grep and BSD grep share the core flags, though some extended options differ across platforms.

Table
FlagMeaning
-iIgnore case.
-vSelect non-matching lines.
-rRecurse into directories.
-nPrint line numbers.
-cCount matching lines per file.
-lPrint only names of matching files.
-wMatch whole words.
-EUse extended regular expressions.
-A NPrint N lines after a match.
-B NPrint N lines before a match.
-C NPrint N lines of surrounding context.
-oPrint only the matching portion.
bash
grep -n "TODO" src/app.ts
grep -ril "deprecated" src/
grep -Eo '[0-9]{3}-[0-9]{4}' notes.txt

Basic and extended patterns

Basic regular expressions treat some operators differently from extended expressions. Use -E when you want readable alternation, grouping, and repetition operators.

Table
PatternMatches
.Any single character.
^texttext at the beginning of a line.
text$text at the end of a line.
[abc]One character from a, b, or c.
[^abc]One character not in the set.
[0-9]One ASCII digit.
\bword\bWord boundaries in GNU grep word-regex mode.
foo|barAlternation in basic GNU grep syntax.
`foobar`
bash
grep -E '^(ERROR|WARN):' application.log
grep -E '^[[:space:]]*#' config.txt
grep -F 'a+b' literal.txt

Recursive searches and files

Use --include and --exclude-dir to keep recursive searches focused. -F treats the pattern literally and avoids regex interpretation.

bash
grep -rIn --include='*.ts' --exclude-dir=node_modules 'fetch(' .
grep -rIl --exclude-dir=.git 'license' .
grep -R --exclude='*.min.js' 'console.log' web/
Table
OptionPurpose
--include='*.ext'Search only matching filenames.
--exclude='*.min.js'Skip matching filenames.
--exclude-dir=.gitSkip a directory name during recursion.
-FMatch fixed strings, not regex.
-aTreat binary input as text; use deliberately.

Context and structured output

Context output is helpful for logs and configuration files. The -- separator protects patterns beginning with a hyphen.

bash
grep -n -C 2 'connection refused' server.log
grep -n -A 4 '^server {' nginx.conf
grep -oE 'https?://[^ ]+' README.md
bash
printf '%s\n' one two three | grep -n 'two'
printf '%s\n' alpha beta gamma | grep -v '^beta$'

Practical recipes

Exit status is 0 for a match, 1 for no match, and usually 2 for an error. That makes grep useful in shell conditionals.

bash
if grep -q '^enabled=true$' settings.conf; then
  printf 'feature enabled\n'
fi
bash
grep -RhoE 'TODO|FIXME' src/ | sort | uniq -c
grep -RIl 'apiKey' . --exclude-dir=.git --exclude-dir=node_modules
find . -type f -print0 | xargs -0 grep -n 'needle'

References