Awk print matching lines and lines until matched

Below I am trying to use awk. Get a string that matches the regular expression and string just before it matches and prints. I can get a string that matches the regular expression, but not a string immediately before this:

awk '{if ($0!~/^CGCGGCTGCTGG/) print $0}' 
+5
source share
6 answers

In this case, you can easily solve it with grep:

grep -B1 foo file

However, if you need to use awk:

awk '/foo/{if (a && a !~ /foo/) print a; print} {a=$0}' file
+10
source
/abc/{if(a!="")print a;print;a="";next}
{a=$0}
+2
source

gawk '{if (/^abc$/) {print x; print $0};x=$0}' file1 > file2

+1

awk script. , 2 . .

search.awk

{
    a[0]=$0;
    for(i=0;i<2;i++)
    {
       getline;
       if(i==0){
            a[1]=$0;
       }
       if(i==1){
            if($0 ~ /message received/){
                print a[0];     
                print a[1];
                print $0;
            }
       }
    }
}

:

awk '{print $0}' LogFile.log | awk -f search.awk
+1
source

Why not use grep -EB1 '^CGCGGCTGCTGG'

awk do the same for a very long time, see Marco's answer.

0
source

Maybe a little off topic, but I used the answer from belisarius to create my own version of the solution that searches for the Nth record and returns it and the previous line.

awk -v count=1 '/abc/{{i++};if(i==count){print a;print;exit}};{a=$0}' file
0
source

All Articles