Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Awk/sed command to print pattern1 only if patterm 2 macthes

Trying to get the "Log" line printed only if "ref1" is present in the text following the "Log" line

sample text :

Log 0102
............
.....ref1.......
......ref1....
Log 0103
............
.....ref1.......
....
Log 0104
............
.....ref2.......
......

expected result :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Log 0102
Log 0103

result i am getting:

Log 0102
Log 0102
Log 0103

i tried this awk command but not getting results:

awk '/Log*/ line =$0}/ref1/{print line}'

>Solution :

With your shown samples please try following awk code.

awk '
/^Log/{
  if(found){ print value }
  value=$0
  found=""
  next
}
/ref1/{
  found=1
}
END{
  if(found){
     print value
  }
}
' Input_file

OR a one-liner form of above code.

awk '/^Log/{if(found){print value};value=$0;found="";next} /ref1/{found=1} END{if(found){print value}}'  Input_file
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading