2009-04-17

vim - basics of search and replace in substitute command mode

When cleaning up some config file with hundreds of lines, browsing up and down just to find the key word can be eye dazzling, in the pungent way. :)

The good thing about vim is, it is able to find any text you want using the "Search" command (/) in the "Normal" mode (Esc twice any time).

Some of the time, we need to change the search result with a new value. Be it slight change, addition or even removal, vim is definitely up to the job. To quote a few examples :

At the "Command-line" mode (at the Normal mode, type ":") type :
%s/text-to-search/text-to-replace/<additional commands during the search>
to enter the "substitute" command mode.

e.g.
%s/searchme/search-me/g
will search for the text "searchme" and replace with "search-me" in the entire file without confirmation


%s/searchme/search-me/gc
will search for the text "searchme" and replace with "search-me" in the entire file but this time, it will prompt for confirmation before replacing it.


%s/normaltext/normal\ text/g
will search for the text "normaltext" and insert a space in between "normal" and "text". Special characters (e.g. space) will need to be escape with "\".
e.g. "/"  --> "\/", ":" --> "\:", """ --> "\"", "?" --> "\", "$" --> "\?" and rest of it will leave it for you to figure it out. :p


%s/searchme/search-me/gci
will search for the text "searchme" in case-insensitive and replace with "search-me" in the entire file, it will prompt for confirmation before replacing it.
e.g "SeArchMe" and "searchme" would matched.


%s/searchme//gi
would remove any occurrence of the text "searchme", case-insensitive, in the entire file.

the "substitute" command mode also support special characters such as newline (\n or \r), tab (\t), beginning of string (^), end of string ($) and any character (.).

Ciao !!!

No comments: