Grep Cheatsheet
Syntax Reminder
grep [OPTIONS] PATTERN [FILE...]
Always quote your PATTERN. Use grep -E for modern regex syntax.
Matching Modes
| Flag | Mode | Use When |
|---|---|---|
| (default) | BRE (Basic Regex) | Simple literal searches |
-E | ERE (Extended Regex) | Alternation |, grouping (), +, ? |
-P | PCRE2 (Perl-compat) | Lookaheads, lookbehinds |
-F | Fixed String | Dots, brackets, special chars — no escaping |
Core Search Flags
| Flag | Purpose | Example |
|---|---|---|
-i | Case insensitive | grep -i "error" |
-w | Whole word match | grep -w "is" |
-x | Whole line match | grep -x "success" |
-v | Invert (NOT match) | grep -v "DEBUG" |
-e PAT | Multiple patterns | grep -e "err" -e "warn" |
-f FILE | Patterns from file | grep -f patterns.txt |
Output Flags
| Flag | Purpose | Example |
|---|---|---|
-n | Line numbers | grep -n "TODO" |
-H | Always show filename | grep -H "pattern" file |
-l | Only filenames | grep -l "ERROR" /var/log/* |
-c | Count lines | grep -c "WARN" app.log |
-o | Only matching text | grep -o "[0-9]\+" data.txt |
-q | Quiet (exit code) | if grep -q "FAIL" log; then |
--color=auto | Highlight match | grep --color=auto "ERR" |
-m N | Stop after N matches | grep -m 1 "FATAL" |
Context Flags
| Flag | Purpose |
|---|---|
-A N | N lines after match |
-B N | N lines before match |
-C N | N lines before and after |
--no-group-separator | No -- between groups (for piping) |
Files and Directories
| Flag | Purpose | Example |
|---|---|---|
-r | Recursive (no symlinks) | grep -r "TODO" src/ |
-R | Recursive (follow symlinks) | grep -R "pattern" /opt/ |
-I | Skip binary files | grep -rI "api_key" /etc/ |
-a | Force text mode | grep -a "pattern" binary.bin |
--include | Only these globs | --include="*.py" |
--exclude | Skip these globs | --exclude="*.min.js" |
--exclude-dir | Skip directory | --exclude-dir=node_modules |
Common Regex (with -E)
| Pattern | Matches |
|---|---|
^ERROR | Line starts with ERROR |
timeout$ | Line ends with timeout |
[0-9]+ | One or more digits |
colou?r | color or colour |
ERROR|FATAL | ERROR 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/