Friday, May 1, 2009

Interactive Search and Replace in vi

I have found a useful command in vi to perform an interactive search and replace in vi. Suppose that you want to find the string trig and replace it with quart in almost every instance of a file: in such a way that you must interactively confirm which instances to replace and which to leave alone.

The way to do this is, for the above example, i.e. replace trig with quart, is:

:1,$s!trig!quart!cg

You can replace all three ! with some other character. This is useful, for instance, if your search string has a ! in it. The 1 denotes the line that you want to start searching and the dollar sign denotes the line that you want to end at. $ means the last line as per usual.