grep -A -B -C: Print Context Around Matches
grep -A N, -B N, and -C N print N lines after, before, or around each matching line.
A bare match is often not enough; you want the stack trace below it or the request above it. Context flags pull in the surrounding lines.
What it does
grep -A N (--after-context) prints N lines after each match, grep -B N (--before-context) prints N lines before, and grep -C N (--context) prints N lines on both sides. When matches are separated, grep prints a line of -- between the groups.
Common usage
# show the stack trace after an exception line
grep -A 20 "Exception" app.log
# show what led up to an error
grep -B 5 "FATAL" build.log
# 3 lines of context around each match
grep -C 3 "timeout" service.logOptions
| Flag | What it does |
|---|---|
| -A N / --after-context | Print N lines after each match |
| -B N / --before-context | Print N lines before each match |
| -C N / --context | Print N lines before and after |
| --group-separator=<s> | Customize the separator between groups (GNU) |
| --no-group-separator | Omit the -- separators (GNU) |
In CI
Context flags make failure logs far more useful: grep -A 30 "panic:" captures the goroutine dump, grep -B 3 "FAILED" shows the test that led to it. The -- separators can confuse downstream parsers; suppress them with --no-group-separator on GNU grep.
Common errors in CI
The -- group separators are literal output lines and can break a strict line-count or JSON-extraction step; use --no-group-separator (GNU) to remove them. BSD/macOS grep supports -A/-B/-C but not --no-group-separator, so on macOS pipe through grep -v "^--$" instead.