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.
When you want to search for a string of text and replace it with another string of text, you can use the syntax :[range]s/search/replace/. The range is optional; if you just run :s/search/replace/, it will search only the current line and match only the first occurrence of a term.
Basic Find and Replace In Vim, you can find and replace text using the :substitute ( :s ) command. To run commands in Vim, you must be in normal mode, the default mode when starting the editor. To go back to normal mode from any other mode, just press the 'Esc' key.
Open the file in Vim. Press slash (/) key along with the search term like “/ search_term” and press Enter. It will highlight the selected word. Then hit the keystroke cgn to replace the highlighted word and enter the replace_term.
Find and Replace One Occurrence at a TimeExecute a regular search with / . Use the keystroke cgn on the first result to replace it. Type n or N to go to the next result. Use . to replace the occurrence with the same replacement, or go to the next result if you want to keep it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With