Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make grep print the lines below and above each matching line? [duplicate]

Tags:

linux

grep

I have to parse a very large file and I want to use the command grep (or any other tool).

I want to search each log line for the word FAILED, then print the line above and below each matching line, as well as the matching line.

For example:

id : 15 Satus : SUCCESS Message : no problem 

id : 15 Satus : FAILED Message : connection error 

And I need to print:

id : 15 Satus : FAILED Message : connection error 
like image 268
poiuytrez Avatar asked Jul 02 '09 05:07

poiuytrez


People also ask

How do I print above and below lines in grep?

It is possible to print a line above or below (or both) a line having a pattern using grep by using -A , -B or -C flags with num value. Here num denotes the number of additional lines to be printed which is just above or below the matched line.

How do you grep multiple lines after a match?

Use the -A argument to grep to specify how many lines beyond the match to output. And use -B n to grep lines before the match. And -C in grep to add lines both above and below the match!

How do you get 10 lines before and after grep?

You can use the -B and -A to print lines before and after the match. Will print the 10 lines before the match, including the matching line itself.

How do you show lines surrounding grep?

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.


2 Answers

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.

like image 183
pgs Avatar answered Oct 17 '22 09:10

pgs


Use -B, -A or -C option

grep --help ... -B, --before-context=NUM  print NUM lines of leading context -A, --after-context=NUM   print NUM lines of trailing context -C, --context=NUM         print NUM lines of output context -NUM                      same as --context=NUM ... 
like image 26
tefozi Avatar answered Oct 17 '22 07:10

tefozi