How to search and replace word under cursor in Vim

Search and replace in Vim is done using this command: :%s/old/new/.

If you start using Vim a lot, you start seeing a problem with this: you have to type the old string that you want to search and be replaced. If this string is long and complicated, then it is a pain. It would be wonderful if you could magically get the word currently under cursor into this search and replace command.

In Vim, you can do this! Here you go:

  • Navigate cursor to any letter of the word.

  • Press *. This highlights the word and also selects it.

  • Now type the command :%s//new/. Notice that you are not providing any search string. Vim automatically picks up the last searched word for that! 🙂

Tried with: Vim 7.4 and Ubuntu 14.04

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.