100

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.

3
  • You can also use n for next match, and b for back (previous) match. Commented Apr 5, 2015 at 9:01
  • @Orwellophile only n works for me b goes back to default (beginning of the word) # works for me as expected, which goes back to the previous term.
    – JohnnyQ
    Commented Jan 28, 2017 at 1:47
  • @JohnnyQ sorry Johnny, I must have been high on glue. it's n for next and N for previous. It's written on my keyboard so I don't know how I got it wrong. Commented Jan 28, 2017 at 13:21

6 Answers 6

178

Just use * to search for the word under your cursor and then:

:%s//new value/g

This will (s)ubstitute all instances of the word under the cursor with new value.

When you don't specify a search pattern between the // characters, the substitute command uses the last searched pattern.

The g at the end will replace all match instances in each line (default without g is to replace only the first match). If you don't want to specify g every time, you can configure gdefault (but heed the warnings that it can break plugins that don't account for it).

6
  • 3
    And if new value contains an & or a /, just escape it with `\`.
    – Benoit
    Commented Apr 4, 2011 at 16:16
  • @sjas What does :se gd do?
    – yelsayed
    Commented Aug 20, 2013 at 10:12
  • :se gd or :set gdefault tells vim to treat every pattern as if it had a /g modifier at the end (more precisely, it inverts the meaning of the /g flag, so if you use it with gdefault active it will disable the effect) Commented Aug 20, 2013 at 12:46
  • 2
    What if I had the to use the searched word in the string that I am replacing it with. e.g. if the word under my cursor is function_with_a_long_name and I have to replace all it's instances with self.function_with_a_long_name ? Commented Jul 14, 2018 at 11:56
  • @ParthSharma to do this, you can use the default "capture group" \0 which in this case contains the term you pressed * on, so for your example, you'd use the command: :%s//self.\0/g
    – Stew
    Commented Mar 20 at 15:56
107

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.

2
  • 2
    it'd be goot explaining the meaning of each command here :)
    – Bertuz
    Commented Apr 24, 2021 at 14:01
  • 3
    Only 12 years later, to understand the <C-r><C-w> form, and similar forms, you can type :help c_<C-R>_<C-W> and look at vim's help on it.
    – Alex W
    Commented Jun 8, 2023 at 16:39
22

In addition to the other answers, you could shave off some more keystrokes by adding following snippet to your .vimrc file for doing a global search and replace.

" Search and replace word under cursor using F4
nnoremap <F4> :%s/<c-r><c-w>/<c-r><c-w>/gc<c-f>$F/i
4
  • 1
    i love it, best answer on the whole internet for me so far ;) Commented Sep 6, 2015 at 19:58
  • 12 years later, this is the best solution for me. Thanks.
    – Hassen
    Commented Jan 13, 2023 at 21:56
  • what does the part at the end do? this part: <c-f>$F/i Commented Apr 5, 2023 at 12:59
  • 1
    @john_m_kenny - the <c-f> opens the current command in a new buffer where you can edit the command just like you would edit text. The $ sets the cursor to the end of the line. The F searches backwards for a / and the i puts you in insert mode, ready to change the replacement value. Commented Apr 5, 2023 at 16:05
5

I went ahead and whipped up a plugin which lets you just enter the following:

:Dr REPLACEVALUE

https://github.com/chiedojohn/vim-dr-replace

3

Another option is to use gn:

Search forward for the last used search pattern, like with n, and start Visual mode to select the match.
If the cursor is on the match, visually selects it.
If an operator is pending, operates on the match.
E.g., "dgn" deletes the text of the next match.
If Visual mode is active, extends the selection until the end of the next match.
Note: Unlike n the search direction does not depend on the previous search command.

So if you have FOO as last search expression, you can replace its next match with BAR typing cgnBAR<Esc>, and repeat for the following matches with ..

If you want to set the word under the cursor as search expression you can type *N (or *#) to search for the next match and come back.

For example, if your cursor is under the first FOO in this line:

<div class="FOO"><span id="FOO"><b>FOO:</b> FOO</span></div>

and you type *NcgnBAR<Esc>..., you end up with this:

<div class="BAR"><span id="BAR"><b>BAR:</b> BAR</span></div>
1
  • This is a great solution for supervised substitution and I find it more elegant than typing the equivalent explicit search substitution command :%s//BAR/gc. Deserves more upvotes!
    – Stew
    Commented Mar 20 at 16:06
0

It's a feature I also desired! But not only for the word under the cursor, also for a visual selection or a motion.

As a result (and building up on your answers), I added this to my .vimrc:

nnoremap <leader>g :set operatorfunc=SubstituteOperator<cr>g@
vnoremap <leader>g :<c-u>call SubstituteOperator(visualmode())<cr>

function! SubstituteOperator(type)
    if a:type ==# 'v'
        execute 'normal! `<v`>"my'
    elseif a:type ==# 'char'
        execute 'normal! `[v`]"my'
    else
        return
    endif

    let sub = input("substitute '".getreg("m")."' with ... : ")
    execute "%s/".getreg("m")."/".sub."/gc"
endfunction

I can now press things like \sw, \sf; or \si( in normal mode or \s in visual mode and get prompt asking if what I want to substitute my selection with.

(So far I don't know if I want the same prompt as @Lieven...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.