bash – 在最后一次与sed匹配后附加一行

前端之家收集整理的这篇文章主要介绍了bash – 在最后一次与sed匹配后附加一行前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我们假设我有以下输入.
Header
thing0 some info
thing4 some info
thing4 some info
thing4 some info
thing2 some info
thing2 some info
thing3 some info

现在,我想能够像这样在“thing4”的最后一次成功比赛中追加“foo”.

Header
thing0 some info
thing4 some info
thing4 some info
thing4 some info
foo
thing2 some info
thing2 some info
thing3 some info

订单不一定得到保证,但此示例中的顺序编号只是为了表明在某些文本行之前有一个可搜索的关键字,并且它们通常在输入中组合在一起,但不能保证.

使用单个awk,您可以:
awk 'FNR==NR{ if (/thing4/) p=NR; next} 1; FNR==p{ print "foo" }' file file

Header
thing0 some info
thing4 some info
thing4 some info
thing4 some info
foo
thing2 some info
thing2 some info
thing3 some info

早期解决方案:您可以使用tac awk tac:

tac file | awk '!p && /thing4/{print "foo"; p=1} 1' | tac
原文链接:https://www.f2er.com/bash/384859.html

猜你在找的Bash相关文章