Grep Command Cheat Sheet
Search text, logs and code quickly with plain matches, case-insensitive searches, recursive scans, regular expressions, context lines and compressed log checks.
Syntax
Basic search
grep "pattern" file.txtCase-insensitive
grep -i "error" error_logRecursive search
grep -R "wp-login.php" /home/user/public_htmlShow line numbers
grep -n "fatal" error_logCommon searches
| Task | Command |
|---|---|
| Find errors in a log | grep -i "error" error_log |
| Search multiple terms | grep -Ei "fatal|parse error|warning" error_log |
| Search all files in current directory | grep -n "database" ./* |
| Only show matching filenames | grep -Rl "eval(base64" public_html |
| Invert match | grep -v "bot" access.log |
| Whole word match | grep -w "admin" access.log |
Log troubleshooting
Apache 500s
grep " 500 " /usr/local/apache/domlogs/example.com-ssl_logWordPress fatal errors
grep -Ei "fatal|parse error|uncaught" /home/user/public_html/error_logLogin attempts
grep "wp-login.php" example.com-ssl_log | awk '{print $1}' | sort | uniq -c | sort -nr | headSpecific IP
grep "203.0.113.25" example.com-ssl_logRegex patterns
| Pattern | Example |
|---|---|
| Either/or | grep -E "error|warning|fatal" error_log |
| Starts with | grep "^127\.0\.0\.1" access.log |
| Ends with | grep "\.php$" file-list.txt |
| Numeric status codes | grep -E " (404|500|503) " access.log |
| Email-like text | grep -E "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+" file.txt |
Use
-E for extended regex so you can write cleaner patterns with |, + and grouped alternatives.Output controls
Before and after context
grep -C 3 "fatal" error_logAfter context only
grep -A 5 "Stack trace" error_logCount matches
grep -c "wp-login.php" access.logSuppress permission errors
grep -R "pattern" /path 2>/dev/nullCompressed logs
Search gzipped logs
zgrep " 500 " /home/user/logs/example.com-ssl_log.gzRecursive zgrep
zgrep -i "fatal" /home/user/logs/*.gzTips
- Quote your search pattern to avoid shell surprises.
- Use
-iwhen case may vary. - Use
-Rfor recursive searches and--exclude-dirto avoid huge folders. - Use
grep -Ffor fixed strings when you do not need regex.
grep -R --exclude-dir={cache,node_modules,vendor} "pattern" public_html
grep workflows for logs and code
Search common errors
grep -Ein "error|warning|failed|timeout" app.logShow context around matches
grep -Ein -C 3 "database|mysql|timeout" app.logRecursive search excluding cache
grep -RIn --exclude-dir=cache "fatal error" /home/user/public_htmlSearch compressed logs
zgrep -Ei "error|failed" /var/log/*.gzExample grep output
$ grep -Ein "error|failed" app.log
17:ERROR database timeout
28:failed login attempt for admin
44:ERROR payment callback failed
Frequently Asked Questions
How do I make grep case-insensitive?
Use grep -i.
How do I show line numbers with grep?
Use grep -n.
How do I use extended regex with grep?
Use grep -E.
How do I search recursively?
Use grep -R or grep -r followed by the pattern and path.