sed 替换最后一行匹配模式 [英] sed replace last line matching pattern

查看:191
本文介绍了sed 替换最后一行匹配模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个这样的文件:

a
b
a
b

我希望能够使用 sed 来替换文件中包含a"实例的最后一行.所以如果我想用c"替换它,那么输出应该是这样的:

I'd like to be able to use sed to replace just the last line that contains an instance of "a" in the file. So if I wanted to replace it with "c", then the output should look like:

a
b
c
b

请注意,无论它可能遇到多少匹配项,或者所需模式或文件内容可能是什么的详细信息,我都需要它来工作.提前致谢.

Note that I need this to work irrespective of how many matches it might encounter, or the details of exactly what the desired pattern or file contents might be. Thanks in advance.

推荐答案

不完全是 sed 而已:

Not quite sed only:

tac file | sed '/a/ {s//c/; :loop; n; b loop}' | tac

测试

% printf "%s
" a b a b a b | tac | sed '/a/ {s//c/; :loop; n; b loop}' | tac
a
b
a
b
c
b

反转文件,然后对于第一个匹配,进行替换,然后无条件地吞下文件的其余部分.然后重新反转文件.

Reverse the file, then for the first match, make the substitution and then unconditionally slurp up the rest of the file. Then re-reverse the file.

注意,一个空的正则表达式(这里是s//c/)意味着重用之前的正则表达式(/a/)

Note, an empty regex (here as s//c/) means re-use the previous regex (/a/)

除了非常简单的程序之外,我不是 sed 的忠实粉丝.我会使用 awk:

I'm not a huge sed fan, beyond very simple programs. I would use awk:

tac file | awk '/a/ && !seen {sub(/a/, "c"); seen=1} 1' | tac

这篇关于sed 替换最后一行匹配模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆