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:
How this works
It reads through the file line-by-line and does one of three things:
a
, it assigns the current line to the@buffer
array.xyz
, it pushes the current line onto the buffer and prints the contents of the buffer@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 closesta
precedingxyz
.You should of course replace the regexes I used with the actual regexes relevant to your case.