Grep pattern before another pattern and print it all

awkgrepsedtext processing

Given intput:

Via: 1.1.1.1  
not relevant line  
keyword + some text
...
not relevant line N
keyword + some text
...
not relevant line N
Via: 2.2.2.2
not relevant line  
keyword + some text
...
not relevant line N
keyword + some text
...
not relevant line N
Via: 3.3.3.3
not relevant lines
Via: 4.4.4.4
not relevant
Via: 5.5.5.5
not relevant line  
keyword + some text
...
not relevant line N
keyword + some text
...
not relevant line N
not relevant line N
...

Required output:

Via: 1.1.1.1  
keyword + some text A
keyword + some text A
Via: 2.2.2.2
keyword + some text B
keyword + some text C
Via: 5.5.5.5
keyword + some text D
keyword + some text E

keyword string can occur N times in any Via block, or may not occur at all. In the output I need only those Via blocks where keyword occurs together with keyword strings belonging to them. The closest answer I found is here, but I can't make it into what I need.

Best Answer

With sed:

sed -n '/^Via:/{ x; /keyword/p; d; }; /keyword/H; ${ x; /keyword/p; }' input.txt

Or, if you want keyword anchored at the beginning of line:

sed -n '/^Via:/{ x; /\nkeyword/p; d; }; /^keyword/H; ${ x; /\nkeyword/p; }' input.txt
Related Question