我需要使用“sed”找到匹配项,并在该匹配项之前删除 2 行,之后删除 3 行,然后打印输出,我该怎么做?
if the file is not huge, try this:
awk 'NR==FNR{if($0~/matchWord/){for(i=NR-2;i<=NR+3;i++){if(i!=NR)a[i]++}}}\
NR>FNR{if(!(FNR in a))print $0}' file file
I didn't test, but should work.
First off, you do not want to do this in sed. 2nd, your question is ill posed: what do you do if you have a match on lines 5 and 8? Does line 8 get deleted and line 6 is kept? Assuming that's not a concern, this seems to do what you want:
#!/bin/sed -nf 1{ h; d; } H 2,5d g /^\([^\n]*\n\)\{2\}match/!P /^\([^\n]*\n\)\{2\}match/{ s/\n[^\n]*$// N } s/[^\n]*\n// h $p
Note: if the match occurs in the last 3 lines of the file, this does not behave as desired. That case is left as an exercise for the (masochistic) reader.
sed ‘/matchWord/,+3d;:flag;1,2!{P;N;D};N;bflag’ file
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.