:%s/one/two/
will replace the first occurrence of one
with two
. Is there an easy way to replace the last occurrence, instead?
I can't assume it's next to the end-of-line, and there's nothing unique around the last occurrence to 'grab' to use, similar to this:
one two three one two three one two one two one two ...
`sed` command can be used to replace any part of a string or a line of the file in different ways by using regular expression patterns. This tutorial showed the ways to replace the last occurrence of the searching text in a string or a file by using multiple `sed` commands.
Using replace() function. In Python, the string class provides a function replace(), and it helps to replace all the occurrences of a substring with another substring. We can use that to replace only the last occurrence of a substring in a string.
Substitution command In some versions of sed, the expression must be preceded by -e to indicate that an expression follows. The s stands for substitute, while the g stands for global, which means that all matching occurrences in the line would be replaced.
The easiest way would be to allow arbitrary text in front of the match, and specify the matched region using \zs
:
:%s/.*\zsone/two/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With