Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VIM: Finding and replacing first N occurrences of a word

Tags:

vim

vi

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.

like image 835
Ignited Avatar asked Sep 15 '14 03:09

Ignited


People also ask

How do I find and replace every incident of a text string in Vim?

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.

How do I find and replace a word in Vim?

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.

How do I overwrite a word in Vim?

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.

How do we search for old and replace it with new Vim?

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.


2 Answers

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@:
like image 62
romainl Avatar answered Oct 14 '22 06:10

romainl


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.

like image 28
Caek Avatar answered Oct 14 '22 05:10

Caek