grep Advanced
Basic grep is powerful. With regular expressions, it becomes unstoppable.
Context Lines
Sometimes you need the lines around a match:
Stack Traces
When debugging errors in logs, -C 5 or -A 10 often shows you the full stack trace.
Regular Expressions
Basic Regex with grep
Anchors:
^= start of line$= end of line
Extended Regex with -E
For more regex features, use -E (or egrep):
Common Patterns
# IP addresses (rough match)
grep -E '[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+' log.txt
# Email addresses (rough match)
grep -E '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}' file.txt
# URLs
grep -E 'https?://[^ ]+' file.txt
Word Boundaries
-w matches whole words only:
Without -w, "port" also matches "report" and "import."
Multiple Patterns
From File
OR Patterns
Only Print Match
By default, grep prints the whole line. Use -o to print only the match:
Great for extracting specific data.
Quiet Mode
-q returns only exit status, no output:
if grep -q 'error' log.txt; then
echo "Errors found!"
fi
Exit codes:
0= match found1= no match2= error occurred
Color Output
Most systems have this aliased by default.
Excluding Files/Directories
When searching recursively:
For Large Projects
Always exclude node_modules, .git, vendor, etc. They make searches painfully slow.
Real-World Examples
Find Failed SSH Logins
Extract IP Addresses
Find TODO Comments
How do you search for lines starting with 'Error' (at the beginning of the line)?
Quick Reference
| Flag | Effect |
|---|---|
-E | Extended regex |
-w | Whole word only |
-o | Print only match |
-q | Quiet (exit code only) |
-A n | n lines after |
-B n | n lines before |
-C n | n lines context |
--include | Only search matching files |
--exclude-dir | Skip directories |
Key Takeaways
- Use
-Efor extended regex (OR patterns, quantifiers) -wprevents partial word matches-A,-B,-Cshow context around matches-oextracts just the matching text--exclude-dirskips directories likenode_modules^and$anchor to start/end of line
Next: extracting columns with cut.