The grep command is one of the most powerful and frequently used tools in Linux. Short for Global Regular Expression Print, grep searches text files for patterns and returns matching lines. Whether you are analyzing server logs, searching codebases, or filtering command output, mastering grep is essential for every Linux user and administrator.
This guide covers 25+ real-world grep examples, from simple text searches to complex regex patterns and log analysis techniques.
Basic grep Syntax
grep [OPTIONS] PATTERN [FILE...]
# Simple text search
grep "error" /var/log/syslog
grep "404" access.log
grep "root" /etc/passwd
1-5: Essential grep Options
# 1. Case insensitive search (-i)
grep -i "error" /var/log/syslog
grep -i "warning" application.log
# 2. Show line numbers (-n)
grep -n "function" app.py
grep -n "TODO" *.js
# 3. Count matches (-c)
grep -c "404" access.log
grep -c "Failed password" /var/log/auth.log
# 4. Invert match - show NON-matching lines (-v)
grep -v "DEBUG" app.log # Exclude debug lines
grep -v "^#" /etc/ssh/sshd_config # Skip comments
grep -v "^$" config.txt # Skip empty lines
# 5. List only filenames with matches (-l)
grep -l "password" /etc/*.conf
grep -rl "TODO" /var/www/src/
6-10: Context and Multiple Patterns
# 6. Show lines AFTER match (-A num)
grep -A 3 "ERROR" app.log # Show 3 lines after each error
# 7. Show lines BEFORE match (-B num)
grep -B 5 "segfault" /var/log/kern.log
# 8. Show lines AROUND match (-C num)
grep -C 2 "Exception" app.log # 2 lines before and after
# 9. Multiple patterns (-e or -E with alternation)
grep -e "error" -e "warning" -e "critical" syslog
grep -E "error|warning|critical" syslog # Same with extended regex
# 10. Whole word match (-w)
grep -w "root" /etc/passwd # Matches "root" but not "chroot"
grep -w "log" filenames.txt # Matches "log" but not "login"
11-15: Recursive Search and File Filtering
# 11. Recursive search in directories (-r)
grep -r "TODO" /var/www/app/
grep -r "password" /etc/
# 12. Recursive with file type filter (--include)
grep -r --include="*.py" "import os" /project/
grep -r --include="*.conf" "listen" /etc/nginx/
# 13. Exclude files or directories
grep -r --exclude="*.log" "error" /var/
grep -r --exclude-dir=".git" "function" /project/
grep -r --exclude-dir=node_modules --exclude-dir=.git "TODO" .
# 14. Show only the matching part (-o)
grep -oE "[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+" access.log # Extract IP addresses
# 15. Binary file handling
grep -I "pattern" * # Skip binary files
grep -a "text" binary_file # Treat binary as text
16-20: Regular Expressions with grep
# 16. Line anchors (start ^ and end $)
grep "^root" /etc/passwd # Lines starting with "root"
grep "bash$" /etc/passwd # Lines ending with "bash"
grep "^$" file.txt # Empty lines only
# 17. Character classes
grep "[0-9]" file.txt # Lines with any digit
grep "[A-Z]" file.txt # Lines with uppercase letter
grep "[^a-z]" file.txt # Lines with non-lowercase char
# 18. Quantifiers (Extended regex with -E flag)
grep -E "[0-9]{3}" data.txt # 3+ consecutive digits
grep -E "^.{80,}" file.txt # Lines longer than 80 characters
grep -E "colou?r" file.txt # Matches "color" or "colour"
# 19. IP address pattern matching
grep -E "([0-9]{1,3}\.){3}[0-9]{1,3}" access.log
# 20. Email address pattern matching
grep -E "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" contacts.txt
21-25: Real-World Log Analysis Examples
# 21. Find failed SSH login attempts and top attacking IPs
grep "Failed password" /var/log/auth.log | grep -oE "from [0-9.]+" | sort | uniq -c | sort -rn | head
# 22. Extract 404 error URLs from web server logs
grep " 404 " /var/log/nginx/access.log | grep -oE "GET [^ ]+" | sort | uniq -c | sort -rn | head -20
# 23. Monitor errors in real-time (follow mode)
tail -f /var/log/syslog | grep --line-buffered -E "error|warning|critical"
# 24. Find PHP errors in web application logs
grep -E "PHP (Fatal|Warning|Notice)" /var/log/nginx/error.log
# 25. Security audit: find potentially malicious PHP files
grep -rl "eval|base64_decode|exec|system|passthru" /var/www/ --include="*.php"
# BONUS: Combine grep with other tools
# Find top 10 requested URLs
grep -oE "GET [^ ]+" access.log | sort | uniq -c | sort -rn | head -10
# Find slow database queries in PostgreSQL log
grep -E "duration: [0-9]{4,}" /var/log/postgresql/postgresql.log | tail -20
# Search for specific HTTP status codes
grep -E " (500|502|503) " /var/log/nginx/access.log | wc -l
grep Performance Tips
# Use fixed strings for literal search (much faster than regex)
grep -F "exact string" largefile.txt
fgrep "exact string" largefile.txt # Equivalent
# Set locale for faster processing
LC_ALL=C grep "pattern" largefile.txt
# Use parallel processing for large directory searches
find /var/log -name "*.log" -print0 | xargs -0 -P 4 grep -l "error"
# Limit output to first N matches
grep -m 10 "pattern" huge-log-file.log
grep vs. Modern Alternatives
| Tool | Best For | Speed |
|---|---|---|
| grep | Standard text search, always available | Fast |
| ripgrep (rg) | Large codebases, respects .gitignore | Very fast |
| ag (silver searcher) | Code search with smart defaults | Fast |
| awk | Column-based text processing | Fast |
| sed | Stream editing and search-replace | Fast |
Recommended Reading
Master the Linux command line with these comprehensive guides:
Download our grep Command Cheat Sheet for a printable quick-reference with all flags, regex syntax, and common patterns.