Using Grep with Context Options: A Complete Guide
You can use grep along with -A (after), -B (before), or -C (context) options to capture lines containing a string and either the line before or after.
Example:
Let’s assume you’re searching for the string pattern in a file called file.txt.
1. Line containing the pattern + line after (-A):
grep -A 1 "pattern" file.txtThis command prints the line containing pattern and the next line after it. 1 represents the number of lines to show after the match.
2. Line containing the pattern + line before (-B):
grep -B 1 "pattern" file.txtThis command prints the line containing pattern and the previous line before it. 1 represents the number of lines to show before the match.
3. Line containing the pattern + one line before and after (-C):
grep -C 1 "pattern" file.txtThis command prints the line containing pattern, one line before, and one line after the match. 1 represents the number of lines before and after the match.
Examples:
For example, given this content in file.txt:
Line 1Line 2Pattern Match HereLine 4Line 5Line 6-
grep -A 1 "Pattern" file.txtwould output:Pattern Match HereLine 4 -
grep -B 1 "Pattern" file.txtwould output:Line 2Pattern Match Here -
grep -C 1 "Pattern" file.txtwould output:Line 2Pattern Match HereLine 4
These options allow you to customize how much context you want around the matching lines.
This article was written by Qwen, based on content from: ChatGPT