grep With Context: -A and -B
grep -A and -B for log investigation.
Flags
The context flags turn grep from a line-finder into a log-reader. Three flags handle almost every investigative case.
- -A N. Show N lines after each match. Captures what happened next around the matching line.
- -B N. Show N lines before each match. Captures the preceding context that led up to the match.
- -C N. Symmetric N lines on both sides. Shortcut for
-A N -B Nwhen you want both directions. - Cleaner than tail piping. Reads the log in place. No
tail | headjuggling and no risk of cutting context at the wrong line.
Examples
Three patterns recur across log investigations. Memorise these and most grep work becomes muscle memory.
- grep -B5 -A5 ERROR app.log. Surrounding context for every error. Shows what led up and what followed.
- grep -B0 -A20 'starting up' app.log. The full startup sequence per restart. Captures the init log without scrolling.
- grep -A50 'request_id=abc'. The full handling chain for one request. Useful when log lines from many requests interleave.
- grep -E 'ERROR|FATAL' -A3. Multi-pattern with context. Cross-severity scan in one pass.
Limit
grep slows down on multi-GB logs. ripgrep handles the same patterns faster, and centralised log search is the right tool above a certain volume.
- ripgrep for huge files.
rgis a near drop-in with the same flags. Significantly faster on large inputs. - Parallel search. ripgrep parallelises across cores. Multi-GB log investigations finish in seconds rather than minutes.
- File-type filtering.
rg --type lognarrows the search scope without manually globbing. - Indexed log search. Loki, Elastic, or Datadog Logs replace ad-hoc grepping at scale. “Grepping production” is the anti-pattern this catches.