Skip to main content

Context Lines

Often, finding the exact line containing an error is useless if you don't know the state of the application leading up to that error. A Java stack trace, for example, is entirely useless if grep only prints the single line Exception in thread "main".

To solve this, GNU grep allows you to print lines surrounding the match, known as "Context".

The Three Context Flags

  1. -B n (Before): Prints n lines of leading context before the match.
  2. -A n (After): Prints n lines of trailing context after the match.
  3. -C n (Context): Prints n lines of output both before and after the match.

Examples:

# Print the error line, AND the 5 lines preceding it
grep -B 5 "NullPointerException" application.log

# Print the matching function definition, AND the next 10 lines of code
grep -A 10 "def process_data" script.py

# Print the match and 2 lines in both directions
grep -C 2 "FATAL" /var/log/syslog

The Context Separator (--)

When you request context, grep might find multiple matches that are far apart in the file. To prevent the output from looking like one continuous, confusing block of text, grep automatically inserts a separator line consisting of two hyphens (--) between contiguous groups of matches.

# Output of: grep -C 1 "error" file.txt
line 1: user logged in
line 2: database connection error
line 3: retrying connection
--
line 89: transaction started
line 90: syntax error near 'SELECT'
line 91: transaction rolled back
Context in Pipelines

If you are piping the output of grep -C to another processing tool (like awk or sed), the -- separator lines will be passed along as well, which might break your script's logic.

If you must pipe context output, use the --no-group-separator flag to disable the -- insertion.