grep -rn <pattern> <dir>
Search every file under a directory and print file names with line numbers.
grep -rn "listen" /etc/nginx/
/etc/nginx/sites-enabled/default:2: listen 80 default_server;
/etc/nginx/sites-enabled/default:3: listen [::]:80 default_server;
-r- Recurse into directories.
-n- Prefix each match with its line number.
-i- Ignore case.
-l- Print only the names of matching files.
--include='*.conf'- Only search files matching a glob.
grep -E <regex> <file>
Use extended regular expressions: alternation, +, ? and grouping without backslashes.
grep -E "error|timeout|refused" app.log
-E- Extended regex (egrep).
-w- Match whole words only.
-x- The pattern must match the whole line.
grep -v <pattern>
Invert the match to drop noise such as health checks before you read a log.
grep -v "GET /healthz" access.log
-v- Print lines that do not match.
-e P1 -e P2- Several patterns, for example to exclude two kinds of noise.
grep -C <N> <pattern> <file>
Show lines around each match, which is where the cause of a stack trace usually is.
grep -C 3 "Traceback" app.log
-C N- N lines before and after.
-B N- N lines before only.
-A N- N lines after only.
grep -c <pattern> <file>
Count matching lines instead of printing them.
grep -c "ERROR" app.log
137
-c- Count matching lines per file.
-o- Print only the matched part, one match per line.
Gotcha -c counts lines, not occurrences. For every occurrence use grep -o PATTERN | wc -l.
grep -F <literal>
Match a fixed string, so characters like . [ ] * are not treated as regex syntax.
grep -F "[error]" error.log
-F- Fixed-string matching (fgrep).
-f FILE- Read the patterns from FILE, one per line.
grep -oE <regex> | sort | uniq -c
Extract a value from each line and count how often each distinct value occurs.
grep -oE "status=[0-9]+" app.log | sort | uniq -c | sort -rn
9412 status=200
318 status=502
41 status=404
-o- Only the matching part.
uniq -c- Collapse adjacent duplicates with a count; needs sorted input.
sort -rn- Numeric, descending.