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....
Using the grep Command. If we use the option '-A1', grep will output the matched line and the line after it.
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.
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 '.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With