Match patternA and print it only when patternB is matched including the following line

awksedtext processing

I am looking to get all the lines which have the word 'search_string' + the line after it + the line matching 'mod' before it.
I tried:

grep -n 'mod\|search_string' ip | grep --before 1 search_string> inter  
grep -n --after 1 search_string ip >> inter  
sort -t':' -k1,1n -u inter -o op

Is there a better way?

File:

mod start1  
some lines  
mod start2  
other lines  
mod start3  
 many other lines  
 search_string yada yada  
 hello  
 many other lines  
 search_string yada yada  
 bye  
mod start4  
 search_string baba baba  
 this too  
mod start5  

Expected output :

mod start3  
 search_string yada yada   
 hello  
 search_string yada yada  
 bye  
mod start4  
 search_string baba baba  
 this too

Best Answer

awk '
   $0 ~ /mod/ { md=$0 }
   $0 ~ /search_string/ { if(md!="") { print md }; md="" ; print; getline; print }
   '

Explanation:

  • A line containing mod is saved as md.
  • A line containing search_string triggers printing the previously saved md, the line itself and the next line.
  • if(md!="") and md="" are there to make sure you don't get duplicated mod lines when there are many search_string-s under a single mod (mod start3 in your example).

Note:

  • A line containing both mod and search_string will break this logic.