In VIM, is it possible to use the selected text in the substitute clause without retyping it?

断了今生、忘了曾经 提交于 2019-12-03 16:51:34

问题


Let's say I have a word selected in visual mode. I would like to perform a substitution on that word and all other instances of that word in a file by using s//. Is there a way to use the highlighted text in the s/<here>/stuff/ part without having to retype it?


回答1:


Sure. If you selected the word, just "y"ank it, and then type:

:%s/<ctrl-r>"/something else/g

Where is pressing ctrl key with r key, and " is just " character.

All keypresses:

y:%s/<ctrl-r>"/what to put/g<enter>



回答2:


If you searched for your text before you can use

CTRL-R /

to insert the last search item in your search and replace string.

You can check this page for other similar tricks:

http://www.vim.org/htmldoc/insert.html




回答3:


You don't have to yank the word, place your cursor on the word and then:

:%s/<C-r><C-w>/bar/g



回答4:


Another way to access register contents from the command line is via @ variables. So if you yank text into the default register, it'll be in a variable called @".

:exe '%s/' . @" . '/stuff/'

Here's a mapping to make this easy to type:

vmap <Leader>s y:exe '%s/' . @" . '//g'<Left><Left><Left>

Now you can highlight something in visual mode, type \s, type your replacement and hit Enter. depesz's version also makes a good mapping (almost exactly as he typed it):

vmap <Leader>s y:%s/<c-r>"//g<Left><Left>


来源:https://stackoverflow.com/questions/1477652/in-vim-is-it-possible-to-use-the-selected-text-in-the-substitute-clause-without

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!