grep
Overview
grep searches input lines for a pattern. GNU grep supports basic/extended/Perl-like regexes, recursive directory search, and rich context controls. Still the default everywhere; rg (ripgrep) is a popular faster alternative when installed.
Syntax
grep [OPTIONS] PATTERN [FILE...]
grep [OPTIONS] -e PATTERN ... [FILE...]
command | grep [OPTIONS] PATTERNCommon Options
| Option | Description |
|---|---|
-E |
Extended regex (ERE) |
-F |
Fixed strings (no regex) |
-P |
Perl-compatible regex (PCRE) if built-in |
-i |
Case-insensitive |
-v |
Invert match |
-n |
Line numbers |
-H / -h |
With / without filename |
-r / -R |
Recursive (follow / include symlinks differently) |
-I |
Skip binary |
-l / -L |
Files with / without matches |
-c |
Count matches per file |
-A/-B/-C n |
Context after/before/both |
-w |
Whole word |
-o |
Only the match |
-m n |
Stop after n matches per file |
--color=auto |
Highlight |
-q |
Silent (exit status only) |
Key Use Cases
- Filter logs and command output
- Code/config search in trees
- Scripting success/failure via exit status
- Extract substrings with
-o
Examples with Explanations
Basic
grep error /var/log/syslog
grep -i error /var/log/syslogExtended regex
grep -E 'error|warn|fail' app.logFixed string (fast, safe)
grep -F 'https://example.com/path?x=1' urls.txtRecursive code search
grep -RIn --exclude-dir=.git --exclude-dir=node_modules 'TODO' .Context
grep -n -C3 'OutOfMemory' heap.logFiles that match
grep -rl 'Listen 80' /etc/apache2 2>/dev/nullExit status in scripts
if grep -q 'ready' /tmp/status; then
echo ok
fiOnly matching part
grep -oE '[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+' access.log | sort -uInvert
grep -v '^#' /etc/ssh/sshd_config | grep -v '^$'Understanding Output
Default: matching lines. With multiple files, lines are prefixed by filename. Exit codes: 0 match, 1 no match, 2 error.
Common Usage Patterns
Pipe from journalctl
journalctl -u nginx --since today | grep -i errorCount HTTP status codes
grep -oE 'HTTP/[0-9.]+" [0-9]{3}' access.log | awk '{print $NF}' | sort | uniq -cNotes & Pitfalls
- Quote patterns to stop shell globbing.
- Basic regex treats
+/|differently than-E.
- Binary matches print “Binary file … matches”; use
-aor-I.
- For huge repos, consider
rgorgit grep.
Additional Resources
man grep
- GNU grep manual