Substitute the n-th occurrence of a word in vim

Gaurav Dadhania picture Gaurav Dadhania · Jun 19, 2010 · Viewed 17.3k times · Source

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?

Answer

Luc Hermitte picture Luc Hermitte · Jun 19, 2010

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.