Search and replace the word under the cursor
From Vim Tips Wiki
Tip 464 Previous Next created April 27, 2003 · complexity intermediate · author maurice · version 6.0
With this mapping in your vimrc, you can easily enter a command to substitute all occurrences of the word under the cursor:
:nnoremap <Leader>s :%s/\<<C-r><C-w>\>/
Given this mapping, if the cursor is on the word foo and you press \s (assuming the default <Leader>), you will see:
:%s/\<foo\>/
If you now type bar/g and press Enter, you will change all foo to bar. The \< and \> ensure that only complete words are found (the search finds foo but not food).
Alternatively, you could use this mapping so that the final /g is already entered:
:nnoremap <Leader>s :%s/\<<C-r><C-w>\>//g<Left><Left>
Also possible to use the cursor position to identify the word under cursor to remplace it with my_word:
:%s/\k*\%#\k*/my_word/
If you only have a few occurrences to change, you might prefer a manual technique which does not require a mapping.
- Put the cursor on foo.
- Press * to search for the next occurrence.
- Type cw (change word) then bar then press Escape.
- Press n (move to next occurrence) then . (repeat change).
- Repeat last step.
[edit] References
[edit] See also
- Search and replace (comprehensive "see also" list)
- Keystroke Saving Substituting and Searching
- Substitute last search
