grep: how to show lines surrounding each match?

To display lines surrounding a match with grep, use the context control options to show lines before, after, or around the matching line. Here are the key flags:

1. Show Lines Around the Match (-C / --context)

grep -C 2 "pattern" file.txt
  • Shows 2 lines before and after each match.
    Output Format:
...
[non-matching line]  
[matching line]  
[non-matching line]  
--
[next matching line's context]

2. Show Lines Before the Match (-B / --before-context)

grep -B 3 "pattern" file.txt
  • Displays 3 lines preceding each match.

3. Show Lines After the Match (-A / --after-context)

grep -A 1 "pattern" file.txt
  • Shows 1 line following each match.

Example

File (data.txt):

Line 1: Apples
Line 2: Oranges
Line 3: Bananas
Line 4: Grapes
Line 5: Apples

Command:

grep -C 1 "Apples" data.txt

Output:

Line 1: Apples
Line 2: Oranges
--
Line 5: Apples

Key Notes

  • Combine Flags: Use -A, -B, and -C together for custom context.
  • Highlight Matches: Add --color=auto to highlight the matched pattern:
  grep -C 2 --color=auto "pattern" file.txt
  • Continuous Context: Use -U (if supported) to avoid splitting context blocks for adjacent matches.
  • Line Numbers: Add -n to show line numbers:
  grep -n -C 1 "pattern" file.txt

Quick Reference

FlagMeaningExample
-C NUMN lines around matchgrep -C 2 "error" log
-B NUMN lines before matchgrep -B 1 "warning" log
-A NUMN lines after matchgrep -A 3 "info" log

Result: You can now easily inspect the context of matches in logs, code, or text files!

Leave a Reply

Your email address will not be published. Required fields are marked *