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/
:%s/word/newword/count
And other commands that i could find on google. But none of them works.
EDIT:: Vim commands is preferred. But Vim script can also be used. I don't have any prior experience in vim scripting.
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@:
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.
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.
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