Vim :s replace first N < g occurrences on a line

Building on the :s/pattern/replacement/gc idea from Samus_ (which seems to be the simplest way to ensure correct operation when pattern is contained within the replacement string), to replace the 2nd through 4th occurrences on a single line:

:call feedkeys("nyyyq") | s/pat/string/gc

feedkeys() is a function that stuffs the input string into the keyboard input queue. The point is to do the counting upfront so you don't have to worry about losing count or getting interrupted.

For a more general case, to replace the Mth through Nth occurrences on a single line for N greater than or equal to a very large M:

:call feedkeys(repeat("n", M-1) . repeat("y", N-M+1) . "q") | s/pat/string/gc

Replace M and N with the values you want (you can even let vim do the trivial mental arithmetic if you don't want to do it yourself). Note that . is VimL's string concatenation operator. Obviously this only saves keystrokes for large M. If you use this functionality frequently, it may save you time to put the above in a custom command or function of some sort, as it is quite a bit to type.


For the first question I would do:

:s/a/b
&&

The second is trickier, I don't know a way to do it automatically but you can make vim prompt you on each match like this:

:s/a/b/gc

Then you reply "no" to the first n matches and "yes" to the others.


a a a a a
a a a a a
a a a a a
a a a a a
a a a a a
a a a a a
a a a a a

:3,6g/^/let i=0 | while i<3 | s/a/b/ | let i+=1 | endwhile

a a a a a
a a a a a
b b b a a
b b b a a
b b b a a
b b b a a
a a a a a