AIX Tip of the Week

AIX Tip of the Week: vi Editor Part I, Search/Replace

Audience: AIX Users

Date: May 14, 1999

From the Dr. Strangelove, or How I Learned to Love the vi Editor file: Although difficult to learn, the vi editor is well worth the effort because the skill is portable between all Unix implementations. But more importantly, vi has powerful editing capabilities that can significantly enhance your productivity. This is the first in a series of tips that will illustrate some these capabilities.

There are several formats for searching/replacing test in vi. One relatively simple format is:


Where "range" indicates which lines to restrict the search/replace. The "range" can be absolute or relative line numbers, as well as search criteria. A few examples will illustrate the use of this format.

vi Command Description
%s/red/blue/ Replace first occurrence (in each line) of red with blue on all lines. The % is shorthand for all lines. Other shorthand notations include . (period) for the current line and $ for the last line in the file.
%s/red/blue/g Replace all occurrences of red with blue on all lines The g indicates all occurrences on a line. The g can be replaced with a number [1,2,...] to change only the n'th occurrence on each line.
45,54s/red/blue/ Replace first occurrence of red with blue on lines 45 through 54.
.,+5s/red/blue/ Replace first occurrence of red with blue starting at the current line for the next 5 lines.
/abc/,/xyz/s/red/blue/ Replace first occurrence of red with blue starting at at the next line containing abc through the first line containing xyz You could also use /xyz/-4 to indicate the line before xyz.

The "range" concept applies to almost all vi commands. For example, 20,40dd will delete lines 20 through 40, .,$dd will delete the current line through the end of the file, and /abc/,/xyz/dd will delete the next line containing "abc" through the line containing "xyz."

Comment: The search/replace commands should be prefaced with the "[ESC]:" keystroke combination. It has been left out here for clarity.