Ubuntu – grep to return Nth and Mth lines before and after the match

awkcommand linegrep

I know that with grep I can use the fields -A and -B to pull previous and next lines from a match.

However they pull in all lines between the match based on however many lines are specified.

grep -r -i -B 5 -A 5 "match" 

I'd like to only receive the 5th line before a match and the 5th line after the match in addition to the matched line and not get the lines between.

Is there a way to do this with the grep?

Best Answer

The tool you want to use is called sift. This is basically a grep on steroids. Grep in parallel. Sift has a huge amount of options to do exactly what you want - specifically to return a particular line relative to a match(s) which may/may not be followed by /preceded by some text.

It amazes me that sift is not mainstream gnu as it was written in the go language but installs on Linux just fine. IT searches in parallel using all cpus huge quantities of text where grep just takes weeks to do the same.

Sift website - see examples

Related Question