Regex – awk print matching line and line before the matched

awkregex

Following is what I am trying to do using awk. Get the line that matches the regex and the line immediately before the matched and print. I can get the line that matched the regex but not the line immediately before that:

awk '{if ($0!~/^CGCGGCTGCTGG/) print $0}' 

Best Answer

In this case you could easily solve it with grep:

grep -B1 foo file

However, if you need to to use awk:

awk '/foo/{if (a && a !~ /foo/) print a; print} {a=$0}' file