Friday, 31 October 2014

Recover everything between two lines matched with grep

I frequently need to recover everything between two lines (that I can match with grep).

some text
random text
random text
other text
Let's say I want to retrieve the 'random text' lines but have no clue of what it looks like. I however know that the previous line contains the unique 'some text' string and that the line just after the random text I want to retrieve contains the unique 'other text' string.
Note the previous and next lines can contain any other text on them as long as I have a pattern I can match with grep.

Here is how I solve that problem;

Find the pattern before and return it with 999999 lines after

grep 'some text' -A 999999

Remove the first line of the previous results (start at line two)

tail -n +2

Find the pattern following our random text and return it with 999999 lines before it 

grep 'other text' -B 999999

Skip the last line of these results

head -n -1

Put together we get

cat file.txt |  grep 'some text' -A 999999 | tail -n +2 | grep 'other text' -B 999999 | head -n -1