我需要在“错误:”之前找到最新出现的“ GET”(GET zzzz),并捕获其间的所有文本。
GET xxxxx
GET yyyyy
GET zzzzz
Some text
more text
error: this is an error
能做到吗?
谢谢,awk解决方案有效,但是可以通过最后一次出现“错误:”来进一步改善这一点吗?
GET xxxxx
GET yyyyy
GET zzzzz
Some text
more text
error: this is the first error
GET xxxxx
GET yyyyy
GET zzzzz
Some text
more text
error: this is the last error
请尝试以下awk
解决方案:
awk '
/^GET/ { delete lines; c=0; inBlock=1 }
/^error:/ { for(i=1; i<=c; ++i) print lines[i]; print; exit }
inBlock { lines[++c] = $0 }
' file
假定仅必须打印1个块,并且error:
还应打印该行。(更新:请参见下面的解决方案,该解决方案仅打印最后一个块)。
/^GET/ { delete lines; c=0; inBlock=1 }
lines
每当GET
在行的开头遇到字符串时,就开始在变量中建立一个行数组。/^error:/ { for(i=1; i<=c; ++i) print lines[i]; print; exit }
error:
在行的开头匹配字符串,并打印出到目前为止建立的所有行,然后显示当前行,然后退出。inBlock { lines[++c] = $0 }
将以最新行开头的每一行添加GET
到数组中。根据OP的要求更新:
要报告(仅)以结尾的最后一个块error:
,请使用以下命令:
awk '
/^GET/ { delete lines; c=0; inBlock=1 }
inBlock { lines[++c] = $0 }
/^error:/ { inBlock=0; }
END { for(i=1; i<=c; ++i) print lines[i] }
' file
这与第一个解决方案的不同之处在于,后面的块仅替换了先前的块,因此最后一个块“获胜”,然后END
在Awk脚本的块中处理完所有输入后将其打印出来。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句