In linux vi command, how can I perform a global search and replace?

To perform a global search and replace in vi, use the search and replace command in command mode:
:%s/search_string/replacement_string/gc

To control the no. of lines being searched through:

The % is a shortcut that tells vi to search all lines of the file for search_string and change it to replacement_string. Of course, you can declare the search and replace for only the current line by removing the % sign.

Furthermore, you can also determine the lines being searched through by defining [start_line_no],[end_line_no] instead of putting %. E.g. :1,10 s/search_string/replacement_string/gc means search from the 1st to 10th line.

To control the occurrences being affected and replaced:

The global ( g ) flag at the end of the command tells vi to continue searching for other occurrences of search_string. If you’ve removed the global ( g ) flag, then only the first occurrence will be affected and replaced.

To confirm each replacement, add the confirm ( c ) flag after the global flag.

February 10th, 2009 @ 04:56 PM • Filed under Linux