grep
Quick Reference
Section titled “Quick Reference”grep [options] "pattern" filecommand | grep [options] "pattern"Essential Flags
Section titled “Essential Flags”| Flag | Purpose | Example |
|---|---|---|
-i | Case-insensitive | grep -i "error" log.txt |
-r / -R | Recursive (search directories) | grep -r "TODO" src/ |
-n | Show line numbers | grep -n "main" app.py |
-c | Count matching lines | grep -c "404" access.log |
-l | List filenames with matches only | grep -rl "password" /etc/ |
-L | List filenames without matches | grep -rL "license" src/ |
-v | Invert match (show non-matching lines) | grep -v "^#" config.conf |
-w | Match whole words only | grep -w "port" config.txt |
-o | Print only matched part | grep -oP '\d+\.\d+\.\d+\.\d+' log.txt |
-A N | Show N lines after match | grep -A 3 "error" log.txt |
-B N | Show N lines before match | grep -B 2 "error" log.txt |
-C N | Show N lines around match | grep -C 5 "panic" syslog |
-E | Extended regex (same as egrep) | `grep -E “(error |
-P | Perl-compatible regex | grep -P "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" file |
-q | Quiet mode (exit code only) | grep -q "root" /etc/passwd && echo "found" |
--include | Filter file types in recursive search | grep -r --include="*.py" "import" . |
--exclude-dir | Skip directories | grep -r --exclude-dir=node_modules "TODO" . |
--color | Highlight matches | grep --color=auto "error" log.txt |
Common Patterns
Section titled “Common Patterns”Filter comments and blank lines from config
Section titled “Filter comments and blank lines from config”grep -v "^#" /etc/ssh/sshd_config | grep -v "^$"Find IPs in a file
Section titled “Find IPs in a file”grep -oP '\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b' access.logSearch for a string across a codebase
Section titled “Search for a string across a codebase”grep -rn --include="*.js" "addEventListener" src/Count occurrences per file
Section titled “Count occurrences per file”grep -rc "error" /var/log/ | grep -v ":0$"Use in pipelines
Section titled “Use in pipelines”ps aux | grep nginxcat /etc/passwd | grep -c "/bin/bash"dmesg | grep -i "usb"history | grep "ssh"grep vs egrep vs fgrep
Section titled “grep vs egrep vs fgrep”| Command | Equivalent | Regex type |
|---|---|---|
grep | — | Basic regex (BRE) |
egrep | grep -E | Extended regex (ERE) — +, ?, ` |
fgrep | grep -F | Fixed strings (no regex, fastest) |
egrep and fgrep are deprecated aliases but still work everywhere.
Useful Regex Patterns
Section titled “Useful Regex Patterns”| Pattern | Matches |
|---|---|
^ | Start of line |
$ | End of line |
. | Any single character |
* | Zero or more of preceding |
+ (ERE) | One or more of preceding |
[a-z] | Character range |
[^0-9] | Not a digit |
\b | Word boundary (with -P) |
\d | Digit (with -P) |
See Also
Section titled “See Also”- ripgrep (
rg) — faster recursive search, respects.gitignore, better defaults. Drop-in replacement for mostgrep -ruse cases.