Cheatsheet: grep

Last updated 2026-06-21

Basic searching

Search for a pattern in a file

grep 'error' app.log

Search case-insensitively

grep -i 'warning' app.log

Show matching line numbers

grep -n 'TODO' src/app.js

Show only the matching text

grep -o '[0-9]+' access.log

Count matching lines

grep -c 'failed' app.log

Recursive and file filtering

Search recursively under a directory

grep -R 'function login' src/

Show only files that contain a match

grep -Rl 'apiKey' src/

Show only files that do not contain a match

grep -RL 'license' .

Search only matching file names

grep -R --include='*.ts' 'interface User' src/

Exclude a directory during recursive search

grep -R --exclude-dir=node_modules 'TODO' .

Matching modes

Invert the match to show non-matching lines

grep -v '^#' config.ini

Match a whole word

grep -w 'cat' words.txt

Match a whole line exactly

grep -x 'enabled=true' config.ini

Treat the pattern as a fixed string, not a regex

grep -F 'a.b[c]' file.txt

Use extended regular expressions

grep -E 'error|warning|fatal' app.log

Use multiple patterns

grep -e 'timeout' -e 'refused' app.log

Context and pipelines

Show lines after each match

grep -A 3 'Exception' app.log

Show lines before each match

grep -B 2 'Exception' app.log

Show lines before and after each match

grep -C 2 'Exception' app.log

Search command output through a pipe

ps aux | grep '[n]ginx'

See also: