gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 22:04:03 25 4
gpt4 key购买 nike

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

sed 's/pattern/replacement/'

和所有匹配使用
sed 's/pattern/replacement/g'

如何只更换 最后 匹配,不管之前有多少匹配?

最佳答案

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

$ # 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

进一步阅读:
  • Buggy behavior if word boundaries is used inside a group with quanitifiers - 例如:echo 'it line with it here sit too' | sed -E 's/with(.*\bit\b){2}/XYZ/' 失败
  • Greedy vs. Reluctant vs. Possessive Quantifiers
  • Reference - What does this regex mean?
  • sed manual: Back-references and Subexpressions
  • 关于sed - 如何只用sed替换一行中的最后一场比赛?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46970466/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com