Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substitute the n-th occurrence of a word in vim

I saw other questions dealing with the finding the n-th occurrence of a word/pattern, but I couldn't find how you would actually substitute the n-th occurrence of a pattern in vim. There's the obvious way of hard coding all the occurrences like

:s/.*\(word\).*\(word\).*\(word\).*/.*\1.*\2.*newWord.*/g 

Is there a better way of doing this?

like image 527
Gaurav Dadhania Avatar asked Jun 19 '10 00:06

Gaurav Dadhania


People also ask

How do I change a whole word in Vim?

Basic Find and Replace In Vim, you can find and replace text using the :substitute ( :s ) command. To run commands in Vim, you must be in normal mode, the default mode when starting the editor. To go back to normal mode from any other mode, just press the 'Esc' key.

How do I go to a specific word in Vim?

One can search forward in vim/vi by pressing / and then typing your search pattern/word. To search backward in vi/vim by pressing ? and then typing your search pattern/word. Once word found in vim, you can press the n key to go directly to the next occurrence of the word in backwards.

How do you go back one word in Vim?

Use b to go back a word.


1 Answers

For information,

s/\%(\(pattern\).\{-}\)\{41}\zs\1/2/

also works to replace 42th occurrence. However, I prefer the solution given by John Kugelman which is more simple -- even if it will not limit itself to the current line.

like image 54
Luc Hermitte Avatar answered Oct 05 '22 04:10

Luc Hermitte