awk command to print last 5 rows if matched

2019-09-03 08:03发布

问题:

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