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
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
这个怎么样?
awk '(NR>1){{a[NR]=$0;if($0~/<\/ABC>/){for(i=NR-4;i<=NR;i++){print a[i]}}}}' input.txt
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.