Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk print matching line and line before the matched

Tags:

regex

awk

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}' 
like image 861
Sudeep Avatar asked Feb 03 '11 20:02

Sudeep


2 Answers

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
like image 64
marco Avatar answered Nov 15 '22 12:11

marco


/abc/{if(a!="")print a;print;a="";next}
{a=$0}
like image 37
Dr. belisarius Avatar answered Nov 15 '22 12:11

Dr. belisarius