Tuesday, June 28, 2011

vi - find and replace

The vi editor is a powerful text editor available on most unix systems. To find and replace text in vi, run the following command:

:%s/original/replacement/g
If you'd like to be a little more careful about which instances of the original string are replaced, add the 'c' option to the end to enable checking:

:%s/original/replacement/gc
Replacing text around a string can be accomplished with a regex:

:%s/abc\(.*\);/def\1;/g
The command above replaces lines of the form abcblah; with defblah; preserving the blah, whatever it may be. The escaped parentheses form a regex group and can be referenced later using \1, \2, \3, etc. (the number corresponding to the group).