如何根据条件删除grep行?

时间:2015-09-16 21:02:47

标签: linux bash ubuntu grep

我想使用grep删除以]:结尾的文件中的所有行,以便下一行以I开头或达到EOF。

即:删除所有以]: 结尾的行,然后后跟一行以文件结尾I开头。

鉴于以下内容:

I am an invalid line ]:
I am a valid line ]:
some text
some text
some text
I am a valid line ]:
some text
I am an invalid line ]:
I am a valid line ]:
some text
some text
some text

输出应为

I am a valid line ]:
some text
some text
some text
I am a valid line ]:
some text
I am a valid line ]:
some text
some text
some text

请注意第1行和第8行I am in invalid line ]:已删除,因为它以]:结尾,下一行以I开头

3 个答案:

答案 0 :(得分:1)

grep -v 'invalid' file.txt

应该这样做。使用-v,您要求选择与该条件不匹配的行。

示例:

$ cat ~/test.txt
I am an invalid line ]:
I am a valid line ]:
some text
some text
some text
I am a valid line ]:
some text
I am an invalid line ]:
I am a valid line ]:
some text
some text
some text

$ grep -v 'invalid' ~/test.txt
I am a valid line ]:
some text
some text
some text
I am a valid line ]:
some text
I am a valid line ]:
some text
some text
some text

根据问题更改进行更新

sed ':a;N;$!ba;s/]:\nI/]:xxx\nI/g' ~/test.txt | grep -v 'xxx'

使用此方法,我将]:\nI替换为]:xxx\nI。看看我如何在以]:结尾的行后面注入xxx - 换行符-I?然后我grep并删除那些xxx

的行

答案 1 :(得分:1)

这个awk应该适合你的要求:

awk '/\]:$/{pno=NR;prec=$0;next} pno && !(/^I/ && NR==pno+1){print prec; pno=0} 1' file

<强>输出:

I am a valid line ]:
some text
some text
some text
I am a valid line ]:
some text
I am a valid line ]:
some text
some text
some text

<强>解体:

/\]:$/{pno=NR;prec=$0;next}  # if ]: is at line end store line # and line and move to next
pno && !(/^I/ && NR==pno+1)  # if next row starts with I and we have prev vars set
{print prec; pno=0}          # print previous line and rest prev line # to 0
1                            # default action to print current record

答案 2 :(得分:0)

所有其他答案对我来说似乎有些过分,所以也许我错过了一些东西,但是:

sed 'N;/]:\nI/D'