The search option accepts most of the standard Unix pattern matching language. (See the Wildcard section.) Suppose I had a file that contained the following text:
There was a young man of Milan
Here are a few examples (using this text) that you will probably never use but may find inspiring:
/[a-z]aswill search for any lowercase letter followed by as. In this example, it would find was and last but not as or asked.
/[^c]anwill search for any an preceded by any character other than a c. In our text it would find Milan but not scan or can.
/^[A-Z].*\. *$will search for any line that begins with a capital letter and ends with a period and any number of blanks. Our only match in the example text would be with the last line.
All of these search patterns can be used in the search and replace command that takes on the following structure:
:s/search_string/replacement_string/gThis command replaces every search_string on the current line with replacement_string. Omitting the g (global) flag at the end of the command will cause only the first occurrence of search_string to be altered. Often you may wish to confirm each replacement. This can be done with the confirm flag c. The confirm flag should be placed after or in place of the g flag. Suppose I had the following line:
Give a skeptic and inch... and he'll take a mile.
:s/take a mile/measure it/I would be left with
Give a skeptic and inch... and he'll measure it.
Any command that begins with a ":" is called a line mode command and performs its duty on the line the cursor is currently on. However, you can override vi's default of operating only on the current line by preceding them with a range of line numbers. For example, if I wanted to replace guy with gal on lines 32 through 56 I would type
:32,56s/guy/gal/gOmitting the g would cause only the first occurrence of guy in each line to be replaced. The "." and "$" play a special role in this sort of designation. "." indicates the current line, and "$" indicates the last line of the file. Therefore, if I wanted to delete1 from the current line to the end of the file I would enter:2
:.,$dI could even do something like:
:.,/Edison/dwhich would delete from the current line to the next line that contained Edison.
One other shortcut that might be worth mentioning is that 1,$ and % both indicate all the lines in the file. Therefore,
:%s/search_string/replacement_string/gdo exactly the same thing.
2 The same could be accomplished by typing dG.
© 1993-2000 Christopher C. Taylor