如何只用 sed 替换一行中的最后一场比赛?

How to replace only last match in a line with sed?

使用 sed,我可以使用

替换一行中的第一个匹配项
sed 's/pattern/replacement/'

所有匹配使用

sed 's/pattern/replacement/g'

如何只替换 最后一个 匹配,而不管之前有多少匹配?

从我在其他地方发布的内容复制粘贴:

$ # replacing last occurrence
$ # can also use sed -E 's/:([^:]*)$/-/'
$ echo 'foo:123:bar:baz' | sed -E 's/(.*):/-/'
foo:123:bar-baz
$ echo '456:foo:123:bar:789:baz' | sed -E 's/(.*):/-/'
456:foo:123:bar:789-baz
$ echo 'foo and bar and baz land good' | sed -E 's/(.*)and/XYZ/'
foo and bar and baz lXYZ good
$ # use word boundaries as necessary - GNU sed
$ echo 'foo and bar and baz land good' | sed -E 's/(.*)\band\b/XYZ/'
foo and bar XYZ baz land good

$ # replacing last but one
$ echo 'foo:123:bar:baz' | sed -E 's/(.*):(.*:)/-/'
foo:123-bar:baz
$ echo '456:foo:123:bar:789:baz' | sed -E 's/(.*):(.*:)/-/'
456:foo:123:bar-789:baz

$ # replacing last but two
$ echo '456:foo:123:bar:789:baz' | sed -E 's/(.*):((.*:){2})/-/'
456:foo:123-bar:789:baz
$ # replacing last but three
$ echo '456:foo:123:bar:789:baz' | sed -E 's/(.*):((.*:){3})/-/'
456:foo-123:bar:789:baz

进一步阅读:

一个有趣的方法是使用 rev 反转每行的字符并向后写你的 sed 替换。

rev input_file | sed 's/nrettap/tnemecalper/' | rev

这可能对你有用 (GNU sed):

sed 's/\(.*\)pattern/replacement/' file

使用贪婪吞噬模式space,然后正则表达式引擎将通过该行返回并找到第一个匹配项,即最后一个匹配项。