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

Viewed 39

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 :

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}'
3 Answers

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 awk '/^Log/{if(found){print value};value=$0;found="";next} /ref1/{found=1} END{if(found){print value}}' Input_file

Using gnu-awk this is fairly simple with custom RS:

awk -v RS='(^|\n)Log ' '/ref1/ {printf "Log %s\n", $1}' file

Log 0102
Log 0103

Here -v RS='(^|\n)Log ' sets RS to Log followed by a space. Log should be preceded by start position or a line break.

mawk 'gsub("^|Log [^\n]+|"FS,"\1&\2",$!(NF-=+_<NF)) + \
      gsub("\2[^\1\2]*\1","\n") + \
      gsub("^[\1\2]+|[\1\2]\n[^\1\2]+$",_)^_' RS= FS='ref1'
Log 0102
Log 0103
Related