Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

ubuntu

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?

like image 629
sriram Avatar asked Oct 02 '22 03:10

sriram


People also ask

How do you get 5 lines before and after grep?

You can use grep with -A n option to print N lines after matching lines. Using -B n option you can print N lines before matching lines. Using -C n option you can print N lines before and after matching lines.

How do you grep and show lines before and after?

To also show you the lines before your matches, you can add -B to your grep. The -B 4 tells grep to also show the 4 lines before the match. Alternatively, to show the log lines that match after the keyword, use the -A parameter. In this example, it will tell grep to also show the 2 lines after the match.

How do you go to the next line after grep?

Using the grep Command. If we use the option '-A1', grep will output the matched line and the line after it.

How do you grep above and below?

grep's -A 1 option will give you one line after; -B 1 will give you one line before; and -C 1 combines both to give you one line both before and after, -1 does the same.


1 Answers

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.

like image 344
Jon Lin Avatar answered Oct 23 '22 12:10

Jon Lin