简体   繁体   English

awk命令如果匹配则打印最后5行

[英]awk command to print last 5 rows if matched

I have an xml file. 我有一个xml文件。 I need to print five lines before the matched text. 我需要在匹配的文本之前打印五行。

There may be multiple matches. 可能有多个匹配项。 I am using following awk command which is returning only one row. 我正在使用以下awk命令,该命令仅返回一行。

awk '/<\/ABC>/' file.xml

returns 回报

<ABC>Some Text1</ABC>
<ABC>Some Text2</ABC>
<ABC>Some Text3</ABC>

Expected: 预期:

... previous 4 lines ...
<ABC>Some Text1</ABC>
... previous 4 lines ...
<ABC>Some Text2</ABC>
... previous 4 lines ...
<ABC>Some Text3</ABC>

Cannot use grep -B as per in Solaris : 无法按照Solaris中的方式使用grep -B

grep: illegal option -- B grep: illegal option -- 2 Usage: grep -hblcnsviw pattern file grep:非法选项-B grep:非法选项-2用法:grep -hblcnsviw模式文件

For Solaris: 对于Solaris:

nawk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=2 a=4 s="string" file1

"b" --> the number of lines to print before string "s". “ b”->在字符串“ s”之前要打印的行数。

"a" --> the number of lines to print after string "s". “ a”->在字符串“ s”之后要打印的行数。

Linux: Linux的:

grep -B4 '<ABC>' file.xml

这个怎么样?

awk '(NR>1){{a[NR]=$0;if($0~/<\/ABC>/){for(i=NR-4;i<=NR;i++){print a[i]}}}}' input.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM