Search a pattern and print preceding lines starting with another pattern

greptext processing

I need to grep for a pattern and once I find it, I need to look for another pattern preceding that and print all those lines in between those.

Better example:

1 a
2 a
3 a
4 a
5 a
6 b
7 c
8 d
9 xyz
10 xyz
11 a
12 a

Grep for xyz and then grep for first a preceding xyz line and print all the lines.

Output (first preceding occurrence of a, I don;t care about other a's in the file):

5 a 
6 b
7 c
8 d
9  xyz
10 xyz

Best Answer

Here's a solution in Perl:

perl -nlE '
    if    (/a/)   { @buffer = ($_) }
    elsif (/xyz/) { push @buffer,$_; say for @buffer }
    else          { push @buffer,$_}
' your_file

How this works

It reads through the file line-by-line and does one of three things:

  1. If the current line matches the pattern a, it assigns the current line to the @buffer array.
  2. If the current line matches the pattern xyz, it pushes the current line onto the buffer and prints the contents of the buffer
  3. If none of the two cases above is true, it simply appends the current line to the @buffer array.

Thus, whenever a new line matches the pattern a, the contents of the @buffer are erased and replaced by the current line only. This guarantees you will find the closest a preceding xyz.

You should of course replace the regexes I used with the actual regexes relevant to your case.

Related Question