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

169

I want a way to search in a given text. For that, I use grep:

grep -i "my_regex"

That works. But given the data like this:

This is the test data
This is the error data as follows
. . . 
. . . .
. . . . . . 
. . . . . . . . .
Error data ends

Once I found the word error (using grep -i error data), I wish to find the 10 lines that follow the word error. So my output should be:

. . . 
. . . .
. . . . . . 
. . . . . . . . .
Error data ends

Are there any way to do it?

This question is tagged with bash shell ubuntu

~ Asked on 2012-09-16 06:15:04

The Best Answer is


297

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.

~ Answered on 2012-09-16 06:16:52


39

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

[email protected]:~$ cat out 
line 1
line 2
line 3
line 4
line 5 my_regex
line 6
line 7
line 8
line 9
[email protected]:~$

Normal grep

[email protected]:~$ grep my_regex out 
line 5 my_regex
[email protected]:~$ 

Grep exact matching lines and 2 lines after

[email protected]:~$ grep -A 2 my_regex out   
line 5 my_regex
line 6
line 7
[email protected]:~$ 

Grep exact matching lines and 2 lines before

[email protected]:~$ grep -B 2 my_regex out  
line 3
line 4
line 5 my_regex
[email protected]:~$ 

Grep exact matching lines and 2 lines before and after

[email protected]:~$ grep -C 2 my_regex out  
line 3
line 4
line 5 my_regex
line 6
line 7
[email protected]:~$ 

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.

~ Answered on 2017-07-12 08:12:55


Most Viewed Questions: