Context Lines
Context lines help you understand why a match occurred — the code or log data before and after.
The Three Flags
| Flag | Meaning |
|---|---|
-A N | N lines after the match |
-B N | N lines before the match |
-C N | N lines both sides |
Practical Examples
# See a function signature and its first 15 lines of body
ag -A 15 "def process_payment" src/
# See 5 lines before a crash line (state leading up to it)
ag -B 5 "Segmentation fault" syslog
# Full context for debugging an auth error
ag -C 4 "authentication failed" /var/log/auth.log
Stack Trace Capture
Capture a full Java stack trace (exception + 30 following lines):
ag -A 30 "java.lang.NullPointerException" application.log
Then count unique exception types:
ag -o "java\.lang\.\w+Exception" application.log | sort | uniq -c | sort -nr
Context Separator
Between non-adjacent match groups, ag inserts -- as a visual separator:
app.log
42- connecting to db
43: ERROR: timeout ← match
44- retrying...
--
102: ERROR: auth failed ← match
103- account locked
Suppress the separator for scripting:
ag --no-group-separator -C 2 "ERROR" app.log | process.sh