如何 grep -v 并在匹配后排除下一行?

Beh*_*ooz 17 grep text-processing

如何为与grep正则表达式匹配的每行过滤掉2行?
这是我的最小测试:

SomeTestAAAA
EndTest
SomeTestABCD
EndTest
SomeTestDEFG
EndTest
SomeTestAABC
EndTest
SomeTestACDF
EndTest
Run Code Online (Sandbox Code Playgroud)

显然我试过例如grep -vA 1 SomeTestAA这不起作用。

所需的输出是:

SomeTestABCD
EndTest
SomeTestDEFG
EndTest
SomeTestACDF
EndTest
Run Code Online (Sandbox Code Playgroud)

hee*_*ayl 13

您可以grep-P(PCRE) 一起使用:

grep -P -A 1 'SomeTest(?!AA)' file.txt
Run Code Online (Sandbox Code Playgroud)

(?!AA)是零宽度负前瞻模式,确保没有AAafter SomeTest

测试 :

$ grep -P -A 1 'SomeTest(?!AA)' file.txt 
SomeTestABCD
EndTest
SomeTestDEFG
EndTest
SomeTestACDF
EndTest
Run Code Online (Sandbox Code Playgroud)


Cac*_*tus 9

您可以使用 GNUsedd命令删除一行,并在其前面加上前缀/pat/,+N以选择与模式匹配的行以及后续的N行。在您的情况下,N = 1,因为您只想删除匹配行之后的单个后续行:

sed -e '/SomeTestAAAA/,+1d'
Run Code Online (Sandbox Code Playgroud)


Pra*_* BS 6

尝试使用下面的 GNUsed命令,效果很好

命令

sed  '/SomeTestAA/,+1d' filename
Run Code Online (Sandbox Code Playgroud)

输出

SomeTestABCD
EndTest
SomeTestDEFG
EndTest
SomeTestACDF
EndTest
Run Code Online (Sandbox Code Playgroud)


don*_*sti 5

这是一个适用于任意输入的sed解决方案(即-n没有自动打印):

sed -n '/SomeTestAA/!p          # if line doesn't match, print it
: m                             # label m
//{                             # if line matches
$!{                             # and if it's not the last line
n                               # empty pattern space and read in the next line
b m                             # branch to label m (so n is repeated until a
}                               # line that's read in no longer matches) but
}                               # nothing is printed
' infile
Run Code Online (Sandbox Code Playgroud)

所以输入像

SomeTestAAXX
SomeTestAAYY
+ one line
SomeTestONE
Message body
EndTest
########
SomeTestTWO
something here
EndTest
SomeTestAABC
+ another line
SomeTestTHREE
EndTest
SomeTestAA
+ yet another line
Run Code Online (Sandbox Code Playgroud)

跑步

sed -n -e '/SomeTestAA/!p;: m' -e '//{' -e '$!{' -e 'n;b m' -e '}' -e'}' infile
Run Code Online (Sandbox Code Playgroud)

输出

SomeTestONE
Message body
EndTest
########
SomeTestTWO
something here
EndTest
SomeTestTHREE
EndTest
Run Code Online (Sandbox Code Playgroud)

也就是说,它完全删除了grep -A1 SomeTestAA infile将选择的行:

SomeTestAAXX
SomeTestAAYY
+ one line
--
SomeTestAABC
+ another line
--
SomeTestAA
+ yet another line
Run Code Online (Sandbox Code Playgroud)