awk command to print last 5 rows if matched

烂漫一生 提交于 2019-12-11 19:59:07

问题


I have an xml file. 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 '/<\/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:

grep: illegal option -- B grep: illegal option -- 2 Usage: grep -hblcnsviw pattern file


回答1:


How about this one?

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



回答2:


For 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".

"a" --> the number of lines to print after string "s".

Linux:

grep -B4 '<ABC>' file.xml


来源:https://stackoverflow.com/questions/22149908/awk-command-to-print-last-5-rows-if-matched

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