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

Jan*_*hoł 5 text-processing replace sed

使用sed,我可以使用替换一行中的第一个匹配项

sed 's/pattern/replacement/'
Run Code Online (Sandbox Code Playgroud)

和所有匹配使用

sed 's/pattern/replacement/g'
Run Code Online (Sandbox Code Playgroud)

如何只替换最后一场比赛,而不管它之前有多少场比赛?

Sun*_*eep 6

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

$ # replacing last occurrence
$ # can also use sed -E 's/:([^:]*)$/-\1/'
$ echo 'foo:123:bar:baz' | sed -E 's/(.*):/\1-/'
foo:123:bar-baz
$ echo '456:foo:123:bar:789:baz' | sed -E 's/(.*):/\1-/'
456:foo:123:bar:789-baz
$ echo 'foo and bar and baz land good' | sed -E 's/(.*)and/\1XYZ/'
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/\1XYZ/'
foo and bar XYZ baz land good

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

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

进一步阅读:


fan*_*nts 6

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

rev input_file | sed 's/nrettap/tnemecalper/' | rev
Run Code Online (Sandbox Code Playgroud)


pot*_*ong 5

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

sed 's/\(.*\)pattern/\1replacement/' file
Run Code Online (Sandbox Code Playgroud)

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