如何使用awk在具有特定模式的开始和结束标记之间打印记录?

时间:2018-02-06 10:35:36

标签: shell awk

例如,对于以下消息,我只想提取以“接收消息”开头的节目,以“已处理”结尾,并在其间插入“覆盖”。

Receiving message
Processing 
Processed
dummy 1
dummy 2
Receiving message
Processing
Overriden
Processed
dummy 3
dummy 4
Receiving message
Processing 
Processed
dummy 5

预期产出:

Receiving message
Processing
Overriden
Processed

以下将获取范围,但如何通过匹配“Overriden”再次过滤并打印中间的所有行?

awk '/Receiving message/,/Processed/'

请注意,“已处理”和下一个“接收消息”之间还有其他行,并且不需要这些行。

3 个答案:

答案 0 :(得分:3)

awk应该有效:

awk '/Receiving message/{data=""; p=1}
     p && /Overriden/{p=2}
     p{data=data $0 RS}
     p==2 && /Processed/{printf "%s", data}' file

Receiving message
Processing
Overriden
Processed

答案 1 :(得分:2)

关注awk可能对您有帮助。

awk '
/Receiving message/{
  flag=1
}
/Processed/{
  flag="";
  if(flag2){
   print val RS $0};
  val=flag2=""
}
/Overriden/ && flag{
  flag2=1}
flag{
  val=val?val ORS $0:$0
}
'   Input_file

说明: 现在也为此添加说明:

awk '
/Receiving message/{    ##Checking here if a line has string Receiving message in it then do following:
  flag=1                ##Setting variable flag value as 1 here.
}
/Processed/{            ##Checking here if a line has string then do following:
  flag="";              ##Setting variable flag as NULL here.
  if(flag2){            ##Checking if a variable named flag2 is NOT NULL then do following:
   print val RS $0};    ##Printing the value of variable val and RS(record seprator) and current line then.
  val=flag2=""          ##Nullifying the variables named val and flag2 here.
}
/Overriden/ && flag{    ##Checking string Overriden if it present in a line and variable flag is NOT NULL then do following:
  flag2=1}              ##Setting variable flag2 as 1 here.
flag{                   ##Checking here if variable flag is NOT NULL then do following:
  val=val?val ORS $0:$0 ##Creating variable named val here whose value is concatenating to its own value.
}
'  Input_file           ##Mentioning Input_file name here.

答案 2 :(得分:2)

这已经被问过并回答了一千次,但是写答案比搜索它更容易,所以这里又是:

$ cat tst.awk
/Receiving message/ { f=1 }
f {
    buf = buf $0 ORS
    if ( /Processed/ ) {
        if ( buf ~ /Overriden/ ) {
            printf "%s", buf
        }
        f=0
        buf=""
    }
}

$ awk -f tst.awk file
Receiving message
Processing
Overriden
Processed