Search code examples
regexvimsedsubstitution

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?


Solution

  • You can do this a little more simply by using multiple searches. The empty pattern in the :s/pattern/repl/ command means replace the most recent search result.

    :/word//word//word/ s//newWord/
    or
    :/word//word/ s/word/newWord/
    

    You could then repeat this multiple times by doing @:, or even 10@: to repeat the command 10 more times.

    Alternatively, if I were doing this interactively I would do something like:

    3/word
    :s//newWord/r
    

    That would find the third occurrence of word starting at the cursor and then perform a substitution.