Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the grep after context to be "until the next blank line"?

Tags:

linux

grep

unix

awk

With grep I know how to set the context to a fixed number of lines. Is it possible to show a context based on an arbitrary string condition, like set after-context to "until the next blank line"?

Or possibly some other combination of tools?

Basically I have a log file of contiguous lines, with blank lines separating the "events" I want to search for a string in the log file, but show the whole event....

like image 588
pixelearth Avatar asked Nov 23 '12 18:11

pixelearth


People also ask

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 I grep next 10 lines?

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 I grep blank lines in a file?

To match empty lines, use the pattern ' ^$ '. To match blank lines, use the pattern ' ^[[:blank:]]*$ '. To match no lines at all, use the command ' grep -f /dev/null '.

How do you grep 3 lines before and after?

For BSD or GNU grep you can use -B num to set how many lines before the match and -A num for the number of lines after the match. If you want the same number of lines before and after you can use -C num . This will show 3 lines before and 3 lines after.


2 Answers

It sounds like you need sed:

sed -n '/pattern/,/^$/p' file 

Don't print by default (-n). For lines that match /pattern/ up to an empty line /^$/, print.

like image 116
Jonathan Leffler Avatar answered Sep 18 '22 13:09

Jonathan Leffler


A simple solution is:

awk '/pattern/' RS= input-file 

Setting RS to the empty string makes awk treat blank lines as the record separator, and the simple rule /pattern/ causes awk to print any record that matches the pattern, which can be any extended regular expression.

like image 34
William Pursell Avatar answered Sep 17 '22 13:09

William Pursell