Context Line Syntax
Detailed Syntax Breakdown
The grep context line syntax follows a consistent pattern:
grep -[BAC] <number_of_lines> <pattern> <file>
Context Options Explained
Option |
Full Name |
Behavior |
-B |
Before Context |
Shows lines before match |
-A |
After Context |
Shows lines after match |
-C |
Combined Context |
Shows lines before and after match |
Practical Syntax Examples
Before Context (-B)
grep -B 2 "error" system.log
Displays 2 lines before each "error" match
After Context (-A)
grep -A 3 "warning" application.log
Shows 3 lines following each "warning" match
Combined Context (-C)
grep -C 1 "critical" debug.log
Reveals 1 line before and after each "critical" match
Context Flow Visualization
graph TD
A[Search Pattern] --> B[Context Option]
B --> C{Number of Lines}
C --> D[Matched Lines]
D --> E[Surrounding Context Lines]
Multiple Context Options
You can combine context options for complex searches:
grep -B 2 -A 3 "exception" error.log
Shows 2 lines before and 3 lines after each "exception" match
LabEx Recommendation
Practice these syntax variations in LabEx's interactive Linux environments to master grep context techniques.