Linux text search

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.txt

Case-insensitive

grep -i "error" error_log

Recursive search

grep -R "wp-login.php" /home/user/public_html

Show line numbers

grep -n "fatal" error_log

Common searches

TaskCommand
Find errors in a loggrep -i "error" error_log
Search multiple termsgrep -Ei "fatal|parse error|warning" error_log
Search all files in current directorygrep -n "database" ./*
Only show matching filenamesgrep -Rl "eval(base64" public_html
Invert matchgrep -v "bot" access.log
Whole word matchgrep -w "admin" access.log

Log troubleshooting

Apache 500s

grep " 500 " /usr/local/apache/domlogs/example.com-ssl_log

WordPress fatal errors

grep -Ei "fatal|parse error|uncaught" /home/user/public_html/error_log

Login attempts

grep "wp-login.php" example.com-ssl_log | awk '{print $1}' | sort | uniq -c | sort -nr | head

Specific IP

grep "203.0.113.25" example.com-ssl_log

Regex patterns

PatternExample
Either/orgrep -E "error|warning|fatal" error_log
Starts withgrep "^127\.0\.0\.1" access.log
Ends withgrep "\.php$" file-list.txt
Numeric status codesgrep -E " (404|500|503) " access.log
Email-like textgrep -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_log

After context only

grep -A 5 "Stack trace" error_log

Count matches

grep -c "wp-login.php" access.log

Suppress permission errors

grep -R "pattern" /path 2>/dev/null

Compressed logs

Search gzipped logs

zgrep " 500 " /home/user/logs/example.com-ssl_log.gz

Recursive zgrep

zgrep -i "fatal" /home/user/logs/*.gz

Tips

  • Quote your search pattern to avoid shell surprises.
  • Use -i when case may vary.
  • Use -R for recursive searches and --exclude-dir to avoid huge folders.
  • Use grep -F for fixed strings when you do not need regex.
grep -R --exclude-dir={cache,node_modules,vendor} "pattern" public_html
Real workflows

grep workflows for logs and code

Search common errors

grep -Ein "error|warning|failed|timeout" app.log

Show context around matches

grep -Ein -C 3 "database|mysql|timeout" app.log

Recursive search excluding cache

grep -RIn --exclude-dir=cache "fatal error" /home/user/public_html

Search compressed logs

zgrep -Ei "error|failed" /var/log/*.gz
Example output

Example grep output

$ grep -Ein "error|failed" app.log
17:ERROR database timeout
28:failed login attempt for admin
44:ERROR payment callback failed
FAQ

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.