Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace last occurrence in line

Tags:

vim

:%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 ... 
like image 821
simont Avatar asked Aug 08 '12 13:08

simont


People also ask

How do I change the last occurrence of a string in Unix?

`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.

How do I change the last occurrence of a string in Python?

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.

What is S in sed command?

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.


1 Answers

The easiest way would be to allow arbitrary text in front of the match, and specify the matched region using \zs:

:%s/.*\zsone/two/ 
like image 77
Prince Goulash Avatar answered Sep 30 '22 15:09

Prince Goulash