简体   繁体   English

我需要使用 sed 查找匹配项并删除该匹配项之前的 2 行和之后的 3 行

[英]I need to find a match using sed and deletes 2 lines before this match and 3 lines after it

我需要使用“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. 首先,您不想在sed中执行此操作。 2nd, your question is ill posed: what do you do if you have a match on lines 5 and 8? 第二,您的问题提出来了:如果您在第5行和第8行有比赛,该怎么办? Does line 8 get deleted and line 6 is kept? 第8行会被删除,而第6行会保留吗? 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. 注意:如果匹配发生在文件的最后3行中,则此行为不符合预期。 That case is left as an exercise for the (masochistic) reader. 该案例留给(受虐狂)读者练习。

sed ‘/matchWord/,+3d;:flag;1,2!{P;N;D};N;bflag’ file

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

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