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

sriram picture sriram · Sep 16, 2012 · Viewed 199.6k times · Source

Hi I'm very new to bash programming. I want a way to search in a given Text. For that I use grep function:

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 following the word error. So my output should be:

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

Are there any ways to do it?

Answer

Jon Lin picture Jon Lin · Sep 16, 2012

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.