Skip to main content

Grep Cheatsheet

Syntax Reminder

grep [OPTIONS] PATTERN [FILE...]

Always quote your PATTERN. Use grep -E for modern regex syntax.

Matching Modes

FlagModeUse When
(default)BRE (Basic Regex)Simple literal searches
-EERE (Extended Regex)Alternation |, grouping (), +, ?
-PPCRE2 (Perl-compat)Lookaheads, lookbehinds
-FFixed StringDots, brackets, special chars — no escaping

Core Search Flags

FlagPurposeExample
-iCase insensitivegrep -i "error"
-wWhole word matchgrep -w "is"
-xWhole line matchgrep -x "success"
-vInvert (NOT match)grep -v "DEBUG"
-e PATMultiple patternsgrep -e "err" -e "warn"
-f FILEPatterns from filegrep -f patterns.txt

Output Flags

FlagPurposeExample
-nLine numbersgrep -n "TODO"
-HAlways show filenamegrep -H "pattern" file
-lOnly filenamesgrep -l "ERROR" /var/log/*
-cCount linesgrep -c "WARN" app.log
-oOnly matching textgrep -o "[0-9]\+" data.txt
-qQuiet (exit code)if grep -q "FAIL" log; then
--color=autoHighlight matchgrep --color=auto "ERR"
-m NStop after N matchesgrep -m 1 "FATAL"

Context Flags

FlagPurpose
-A NN lines after match
-B NN lines before match
-C NN lines before and after
--no-group-separatorNo -- between groups (for piping)

Files and Directories

FlagPurposeExample
-rRecursive (no symlinks)grep -r "TODO" src/
-RRecursive (follow symlinks)grep -R "pattern" /opt/
-ISkip binary filesgrep -rI "api_key" /etc/
-aForce text modegrep -a "pattern" binary.bin
--includeOnly these globs--include="*.py"
--excludeSkip these globs--exclude="*.min.js"
--exclude-dirSkip directory--exclude-dir=node_modules

Common Regex (with -E)

PatternMatches
^ERRORLine starts with ERROR
timeout$Line ends with timeout
[0-9]+One or more digits
colou?rcolor or colour
ERROR|FATALERROR or FATAL
[[:digit:]]{4}Exactly 4 digits (portable)
^\s*$Empty / whitespace-only line

Production Pipelines

# Top 10 IPs from access log
grep -E -o "([0-9]{1,3}\.){3}[0-9]{1,3}" access.log \
| sort | uniq -c | sort -nr | head -10

# Strip comments and empty lines from a config
grep -E -v "^#|^[[:space:]]*$" /etc/ssh/sshd_config

# Fast search on large ASCII log (100x speedup)
LC_ALL=C grep -F "session_token" /var/log/large.log

# Live monitoring with instant output
tail -f app.log | grep --line-buffered "ERROR"

# Audit: secrets in source code
grep -rI -E "api_key|password|secret" --include="*.py" /var/www/