删除模式之后的所有内容,包括模式

时间:2019-02-04 16:55:48

标签: string unix awk sed

我有一个类似的文本文件

some
important
content
goes here
---from here--
some 
unwanted content

我正在尝试删除---from here--之后的所有行,包括---from here--。也就是说,所需的输出是

some
important
content
goes here

我尝试了sed '1,/---from here--/!d' input.txt,但并未删除---from here--部分。如果我使用sed '/---from here--.*/d' input.txt,则只会删除---from here--文本。

如何删除包含该图案的图案后的行?

编辑

我可以通过执行第一个操作并将其输出传递给第二个输出来实现,例如sed '1,/---from here--/!d' input.txt | sed '/---from here--.*/d' > outputput.txt
有单步解决方案吗?

5 个答案:

答案 0 :(得分:3)

使用sed的另一种方法:

sed '/---from here--/,$d' file

d(删除)命令适用于从包含---from here--的第一行到文件($)末尾的所有行

答案 1 :(得分:2)

另一种awk方法:

awk '/---from here--/{exit}1' file

如果您具有GNU awk 4.1.0+,则可以添加-i inplace来就地更改文件。
否则请申请| tee file来就地更改文件。

答案 2 :(得分:1)

请尝试以下操作(如果您对awk感到满意)。

awk '/--from here--/{found_from=1} !found_from{print}' Input_file

答案 3 :(得分:1)

我不是很肯定,但是我相信这会起作用:

sed -n '/---from here--/q; p' file

q命令告诉sed在匹配给定行之后退出处理输入行。

答案 4 :(得分:0)

您可以尝试Perl

perl -ne ' $x++ if /---from here--/; print if !$x '

使用您的输入。

$ cat johnykutty.txt
some
important
content
goes here
---from here--
some
unwanted content

$ perl -ne ' $x++ if /---from here--/; print if !$x ' johnykutty.txt
some
important
content
goes here

$
相关问题