How to replace a single word under cursor?

VimReplace

Vim Problem Overview


How do I replace a word under the cursor in Vim.

So instead of using dw then i then the word and then Esc, is there a simpler combination to replace the word under the cursor?

Vim Solutions


Solution 1 - Vim

ciw

(change inner word) will change the whole word under the cursor. Compare with

cw

which will only change the word from the current cursor position. For more info see this SO question/answer.

Solution 2 - Vim

I often find myself wanting to replace one word with another that I have yanked from elsewhere. The problem with the other solutions is that if you attempt to change a word, then your next paste will be that word that you deleted with cw.

Try the following:

1 "This first word should overwrite the second"

yiw 	yank inner word (copy word under cursor, say "first").
... 	Move the cursor to another word (say "second").
viwp 	select "second", then replace it with "first". 

Hope that's what you were looking for.

Solution 3 - Vim

ciw

c   change
iw  inner word

This will delete the word under the cursor (even if the cursor is somewhere in the middle of the word) and enter insert mode.


Also see Vim's documentation for reference:

:help c
:help text-objects

Solution 4 - Vim

If you want to change a word with a previously yanked word, there's another solution to viwp (once you have yanked the first word).

ciw removes the previous word and puts you in insert mode where it was. But then you can use ctrl+r, 0 to insert the contents of register 0 (which contain the previously yanked word).

So:

yiw
[move to next word]
ciw
ctrl+r
0

This works better than viwp because after the first usage you can then repeatedly perform the replacement with .. It also doesn't switch into visual mode and highlight briefly.

Solution 5 - Vim

Try cw - as in 'change word'.

Use http://linuxmoz.com/vi-commands-cheat-sheet/ or any other cheat sheet as a reference.

Solution 6 - Vim

To copy word under cursor press: bvey

To replace the word under cursor press: bvep

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsaythView Question on Stackoverflow
Solution 1 - VimBrian AgnewView Answer on Stackoverflow
Solution 2 - VimEtherealView Answer on Stackoverflow
Solution 3 - VimXophmeisterView Answer on Stackoverflow
Solution 4 - VimConnorView Answer on Stackoverflow
Solution 5 - VimKosma DunikowskiView Answer on Stackoverflow
Solution 6 - VimABNView Answer on Stackoverflow