Contents

sed 替换匹配的最后一个

Contents

https://statics.lshell.com/sed.jpg

今天遇到这个需求,在 stackoverflow 找到了答案,收藏一下。
原答案:https://stackoverflow.com/a/46970532
直接上例子:```

$ # 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/(.*)bandb/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

1
2
3
4

*   [Greedy vs. Reluctant vs. Possessive Quantifiers](https://stackoverflow.com/questions/5319840/greedy-vs-reluctant-vs-possessive-quantifiers)
*   [Reference - What does this regex mean?](https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean)
*   [sed manual: Back-references and Subexpressions](https://www.gnu.org/software/sed/manual/sed.html#Back_002dreferences-and-Subexpressions)