Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VIM: how to replace a word

Tags:

replace

vim

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, what 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

like image 778
Stas Avatar asked Nov 05 '10 13:11

Stas


People also ask

How do I replace a word with yanked in Vim?

Move the cursor to another word (say "third"). Repeat the operation (change word and replace it with "first"). Move the cursor to another word and press . to repeat the change. Yank inner text (text containing cursor which is in quotes).

How do you replace a word in Linux?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

What command is used to overwrite a single word in the Vim EDitor?

Replace mode allows you replace existing text by directly typing over it. Before entering this mode, get into normal mode and put your cursor on top of the first character that you want to replace. Then press 'R' (capital R) to enter replace mode. Now whatever you type will replace the existing text.


1 Answers

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.

like image 62
Benoit Avatar answered Sep 19 '22 05:09

Benoit