In vim, I sometimes have occasion to replace the first few occurrences of a match on a line, but not every one like g
would. e.g.:
a a a a a
to
b b b a a
I know I could use :s/a/b/[enter]:[up][enter]:[up][enter]
, but that's tedious enough at three repetitions, I have lines with potentially 10+ substitutions.
I've tried:
:s/a/b/3g
: vim complained of trailing characters.:s/a/b/3
: changes the first occurrence on this and the following two lines.3:s/a/b
: same as previous.:s/a/b/g3
: changes all occurrences on this and the next two lines.:3s/a/b
: changes the first occurrence on line 3.:/a/,3/a/s/a/b
: changes first occurrence on each line between the nexta
and the third line containinga
in the file (prompting to reverse if necessary).:/a/,/\([^a]*a\)\{3\}/s/a/b/
: changes the first occurrence on each line between this and the next with 3a
s on it (and this wouldn't have been easily extensible to a multi-character search).
And various other addressing patterns, none of which worked. I must say, I've learned a fair amount about the :s
command trying to find an answer to this problem, but I still haven't solved it.
Anyone know how to do this?
(bonus points for specific range, e.g. second through fourth occurrences)
n
and.
, though I didn't think to use them here. Certainly an improvement, thanks.s/a/=something/
should do the trick (:help sub-replace-=
). I'm not fluent enough in Vim to writesomething
right off the bat.:[up][enter]
can be replaced with&
, which still isn't ideal but at least is less painful.