How do I fetch lines before/after the grep result in bash? How do I fetch lines before/after the grep result in bash? bash bash

How do I fetch lines before/after the grep result in bash?


You can use the -B and -A to print lines before and after the match.

grep -i -B 10 'error' data

Will print the 10 lines before the match, including the matching line itself.


This prints 10 lines of trailing context after matching lines

grep -i "my_regex" -A 10

If you need to print 10 lines of leading context before matching lines,

grep -i "my_regex" -B 10

And if you need to print 10 lines of leading and trailing output context.

grep -i "my_regex" -C 10

Example

user@box:~$ cat out line 1line 2line 3line 4line 5 my_regexline 6line 7line 8line 9user@box:~$

Normal grep

user@box:~$ grep my_regex out line 5 my_regexuser@box:~$ 

Grep exact matching lines and 2 lines after

user@box:~$ grep -A 2 my_regex out   line 5 my_regexline 6line 7user@box:~$ 

Grep exact matching lines and 2 lines before

user@box:~$ grep -B 2 my_regex out  line 3line 4line 5 my_regexuser@box:~$ 

Grep exact matching lines and 2 lines before and after

user@box:~$ grep -C 2 my_regex out  line 3line 4line 5 my_regexline 6line 7user@box:~$ 

Reference: manpage grep

-A num--after-context=num    Print num lines of trailing context after matching lines.-B num--before-context=num    Print num lines of leading context before matching lines.-C num-num--context=num    Print num lines of leading and trailing output context.


The way to do this is near the top of the man page

grep -i -A 10 'error data'