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

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

问题描述

由于文件是这样的:

a
b
a
b

我希望能够使用 SED 与一,在该文件的一个实例来代替刚才的最后一行。所以,如果我想用C来取代它,那么输出应该是这样的:

I'd like to be able to use sed to replace just the last line with 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. Thanks in advance.

推荐答案

不太SED不仅:

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

测试

% printf "%s\n" 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 the unconditionally slurp up the rest of the file. Then re-reverse the file.

请注意,一个空正则表达式(这里为取值// C / )意味着重新使用previous正则表达式( / 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天全站免登陆