awk print matching line and line before the matched

Deadly 提交于 2021-02-07 03:05:23

问题


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

回答1:


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



回答2:


/abc/{if(a!="")print a;print;a="";next}
{a=$0}



回答3:


use more straightforward pattern search

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




回答4:


I created the following awk script. Prints the matching line as well as the previous 2 lines. You can make it more flexible from this idea.

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;
            }
       }
    }
}

Usage:

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



回答5:


Why not use grep -EB1 '^CGCGGCTGCTGG'

The awk to do the same thing is very long-winded, see Marco's answer.




回答6:


Maybe slightly off-topic, but I used the answer from belisarius to create my own variation of the above solution, that searches for the Nth entry, and returns that and the previous line.

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


来源:https://stackoverflow.com/questions/4891383/awk-print-matching-line-and-line-before-the-matched

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!