I am editing a file and i want to change only a specific word with another word, but only for first N occurrences. I tried multiple commands
N :s/word/newword/
Using a disposable recording allows you to control exactly how many changes you do:
qq " start recording in register q
/foo<CR> " search for next foo
cgnbar<Esc> " change it to bar
q " end recording
11@q " play recording 11 times
See :help recording
and :help gn
.
Another way, using :normal
:
:norm! /foo<C-v><CR>cgnbar<C-v><Esc> <-- should look like this: :norm! /foo^Mcgnbar^[
11@:
See :help :normal
and :help @:
.
Or simply:
:/foo/|s//bar<CR>
11@:
I'm not sure about specifying the first N occurrences, but I often use this command:
:%s/word/newword/gc
Vim then asks for confirmation of each occurrence of word
so you can selectively change some but not others.
Although a bit longer, you can do:
:call feedkeys("yyyq") | %s/word/newword/gc
to replace the first 3 occurrences and then stop.
You can change the amount of y
's for more or less replacements. (Can also use n
to skip some)
Explanation: this is feeding y
keystrokes into the /c
confirm option of the substitution command.
My PatternsOnText plugin provides (among many others) a command that takes answers in the form of either yyynyn
or 1-5
:
:%SubstituteSelected/word/newword/g 1-5