开发者

VIM: how to replace a word

开发者 https://www.devze.com 2023-01-24 04:12 出处:网络
I guess, the problem is pretty common. Let\'s say, we have a source file and wish to replace some string with another string.

I guess, the problem is pretty common. Let's say, we have a source file and wish to replace some string with another string.

Usually, I use the following command:

:%s/test/testValue/gc

But, w开发者_运维技巧hat if the string is pretty long and we need just to touch it up? It is boring to type something like that:

%s/someLongAndDirtyString/somelongAndDirtystring/gc

Is it possible to place a cursor on someLongAndDirtyString word, press some magic key and get the following in the last line?

%s/someLongAndDirtyString/someLongAndDirtyString/gc

Then we may change the new string a bit and proceed with replacing.

Sure, it is just an idea. Please, provide me with the best way of doing such replacements.

Thanks


You might be interested in this answer I gave on how to use registers, but here are four methods to do that:

Method 1

While editing a command, hit CTRLR then CTRLW to insert word under the cursor.

Also see :help c_CTRL-R

Method 2

Go to your word, hit *, and do :%s//replacement/g. When no search pattern is used, last search pattern, taken from register @/, is used.

Method 3 (you will probably like that one)

Do a :nnoremap <f12> :%s/<c-r><c-w>/<c-r><c-w>/gc<c-f>$F/i (ctrl-f is determined by the 'cedit' option)

You can put this mapping into your .vimrc.
This will map the F12 key to what you want, and your cursor will be left where you want.

Method 4

Go to your word, hit *, and do :%s//CTRLR,//gc
CTRL-R then / inserts contents of your search register.


Well, if your cursor is on the word you want to replace, you can hit * which will highlight and search for the word, and then you can type:

:%s//newstring/gc

and vim will insert the last searched string in between the slashes.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号