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.
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.
To get the n-th line after each match, we can first use grep -An to find each block with n+1 lines. Next, instead of piping it to grep -v, we pipe it to a command that can print every (n+1)-th line. As the output above shows, we've got the 3rd line after each “Performance: BAD” line.
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.
you can try with awk:
awk '/blah/{getline; print}' logfile
If you want to stick to grep:
grep -A1 'blah' logfile | grep -v "blah"
or alternatively with sed:
sed -n '/blah/{n;p;}' logfile
Piping is your friend...
Use grep -A1
to show the next line after a match, then pipe the result to tail
and only grab 1 line,
cat logs/info.log | grep "term" -A1 | tail -n 1
Great answer from raim, was very useful for me. It is trivial to extend this to print e.g. line 7 after the pattern
awk -v lines=7 '/blah/ {for(i=lines;i;--i)getline; print $0 }' logfile
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