VIM: search and replace the first N occurrences of a word

I am editing a file and I want to change only a specific word with a different word, but only for the first N occurrences. I tried several teams

N :s/word/newword/

:%s/word/newword/count

And other commands that I can find on google. But none of them work.

EDIT :: Vim commands are preferred. But you can also use a Vim script. I have no experience with vim scripts.

+6
source share
4 answers

Using a one-time recording allows you to precisely control how many changes you make:

 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 :normal :

 :norm! /foo<Cv><CR>cgnbar<Cv><Esc> <-- should look like this: :norm! /foo^Mcgnbar^[ 11@ : 

See :help :normal and :help @:

Or simply:

 :/foo/|s//bar<CR> 11@ : 
+13
source

Although a little longer, you can do:

 :call feedkeys("yyyq") | %s/word/newword/gc 

to replace the first 3 entries, then stop. You can change the quantity y for more or less substitutions. (You can also use n to skip some)

Explanation: this is giving the y keys to the /c option of the substitution command.

+9
source

My PatternsOnText plugin provides (among many others) a command that takes answers in the form of yyynyn or 1-5 :

 :%SubstituteSelected/word/newword/g 1-5 
+2
source

I am not sure about the definition of the first N occurrences, but I often use this command:

 :%s/word/newword/gc 

Vim then asks for confirmation of each occurrence of the word so that you can selectively change some, but not others.

+1
source

Source: https://habr.com/ru/post/975268/


All Articles