我们假设我有以下输入.
Header
thing0 some info
thing4 some info
thing4 some info
thing4 some info
thing2 some info
thing2 some info
thing3 some info
Run Code Online (Sandbox Code Playgroud)
现在,我希望能够像这样在"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
Run Code Online (Sandbox Code Playgroud)
订单不一定得到保证,但此示例中的顺序编号只是为了表明在某些文本行之前有一个可搜索的关键字,并且它们通常在输入中组合在一起,但不能保证.
小智 8
sed -e "$(grep -n 'thing4' file |tail -1|cut -f1 -d':')a foo" file
Run Code Online (Sandbox Code Playgroud)
使用 shell 和 grep 获取包含该模式的最后一个行号,然后使用该行号作为 sed append 命令的地址。
使用单个 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
Run Code Online (Sandbox Code Playgroud)
较早的解决方案:您可以使用tac + awk + tac:
tac file | awk '!p && /thing4/{print "foo"; p=1} 1' | tac
Run Code Online (Sandbox Code Playgroud)
这可能对你有用(GNU sed):
sed '1h;1!H;$!d;x;s/.*thing4[^\n]*/&\nfoo/' file
Run Code Online (Sandbox Code Playgroud)
将文件放入内存并使用正则表达式的贪婪将所需的字符串放在最后一次出现所需模式之后。
更有效(使用最少内存)但更难理解的是:
sed '/thing4[^\n]*/,$!b;//{x;//p;g};//!H;$!d;x;s//&\nfoo/' file
Run Code Online (Sandbox Code Playgroud)
解释留给读者去琢磨。
| 归档时间: |
|
| 查看次数: |
5208 次 |
| 最近记录: |