使用sed从第一行打印到包含最后一次出现的模式的行?

Modified on: Sat, 30 Jun 2018 12:04:30 +0800

我知道以下命令会打印到某个特定模式的第一次出现,但不包括后面出现的事件:

sed -n '1,/<pattern>/p' <file>

sed '/<pattern>/q' <file>

例如,假设我有一个包含以下行的文件:

this is a cow   
this is a goat  
this is a some fish  
this is a fishie  
this is a fish  
this is a lion  
this is a cat

现在输出:

$ sed '/fish/q' file  

this is a cow  
this is a goat  
this is a some fish 

$ sed -n '1,/fish/p' file  

this is a cow  
this is a goat  
this is a some fish 

我希望输出从第一行开始直到包含最后一次fish的行,即我想要的输出是:

this is a cow   
this is a goat  
this is a some fish  
this is a fishie  
this is a fish 

如何使用sed

进行此操作

最佳答案

试试这个:

$ tac infile | sed -n '/fish/,$p' |tac

一般情况下,如果你在sed命令下运行,你将获得从第一个匹配模式到输入文件结尾的所有行。

$ sed -n '/fish/,$p' file

this is a some fish
this is a fishie
this is a fish
this is a lion
this is a cat

所以我的解决方案是:如果我们在输入文件上运行tac命令,您最后匹配的模式将更改为第一个模式。看到tac infile的结果:

$ tac infile

this is a cat
this is a lion
this is a fish
this is a fishie
this is a some fish
this is a goat
this is a cow

tac命令与cat命令相同,而tac以相反的顺序打印文件。

现在,如果我们运行第一个sed命令,您将获得所有行首先匹配的模式到输入文件的结尾。像:

$ tac infile | sed -n '/fish/,$p'
this is a fish
this is a fishie
this is a some fish
this is a goat
this is a cow

好的,完了。我们只需要再次运行tac命令将这些行反转回原始顺序:

$ tac infile | sed -n '/fish/,$p' |tac
this is a cow
this is a goat
this is a some fish
this is a fishie
this is a fish

完成!


相关问答

添加新评论