Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim - Search and replace the results

I'm getting more and more comfortable with Vim after a few months. BUT, there is only one simple feature I can't get any answer from the web. That is "Search and replace the results". The problem is that I know:

:/keyword to search, and hit enter "keyword" will be highlighted (of course with set hlsearch) n, or N to navigate

:% s/keyword/new_keyword/g to replace all occurences of keyword with new_keyword.

BUT, I would think that there must be a way to search, and replace the matched keyword (highlighted) with any new_keyword WITHOUT doing ":% s/keyword/new_keyword/g", which is a lot of typing considering search & replace is such a day-to-day feature.

Any answers/comments will be greatly appreciated!

like image 334
Khiet Avatar asked Nov 02 '10 21:11

Khiet


People also ask

How do I search and replace in Vim?

Basic Find and Replace In Vim, you can find and replace text using the :substitute ( :s ) command. To run commands in Vim, you must be in normal mode, the default mode when starting the editor. To go back to normal mode from any other mode, just press the 'Esc' key.

How do you replace a word with another word in Vim?

Search for text using / or for a word using * . In normal mode, type cgn (change the next search hit) then immediately type the replacement. Press Esc to finish. From normal mode, search for the next occurrence that you want to replace ( n ) and press . to repeat the last change.

How will you search and replace text in vi?

The % is a shortcut that tells vi to search all lines of the file for search_string and change it to replacement_string . The global ( g ) flag at the end of the command tells vi to continue searching for other occurrences of search_string . To confirm each replacement, add the confirm ( c ) flag after the global flag.


2 Answers

If you've already done a search you can do a substitution for the same pattern by simply leaving out the pattern in the substitute command. eg:

/keyword

searchs for "keyword", and then:

:%s//new_keyword/g

will replace all occurrences of "keyword" with "new_keyword".

like image 159
Laurence Gonsalves Avatar answered Oct 13 '22 20:10

Laurence Gonsalves


Searching and using the dot command (you didn't meantion you are using the dot command, that's why I highlight it) to repeat the last input action is my best bet here.

I use s///g for search and replace.

like image 31
Ronny Brendel Avatar answered Oct 13 '22 21:10

Ronny Brendel