Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Vim, replace all occurrences of current term under cursor

Tags:

vim

If you press * in Vim, the editor will search for the next occurrence of the term in the same file. It saves you from having to type out the term.

Is there a quick way to replace the term currently under the cursor with a new one? One character to issue the command, typing in the new term, then Enter.

like image 543
Muchin Avatar asked Apr 04 '11 16:04

Muchin


People also ask

How to replace all with Vim?

Press y to replace the match or l to replace the match and quit. Press n to skip the match and q or Esc to quit substitution. The a option substitutes the match and all remaining occurrences of the match. To scroll the screen down, use CTRL+Y , and to scroll up, use CTRL+E .

How to replace words in Vim editor?

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.


2 Answers

Just use * and then:

:%s//new value/ 

If you don't specify a pattern, the substitute command uses the last searched one. Depending on the value of gdefault in your configuration, you might need to add a /g modifier to that command.

like image 134
Matteo Riva Avatar answered Oct 12 '22 18:10

Matteo Riva


You can use:

:%s/<c-r><c-w>/new value/g 

where <c-r><c-w> means to literally type CTRL-rCTRL-w to insert the word under the cursor.

like image 35
skeept Avatar answered Oct 12 '22 19:10

skeept