< Zurück | Inhalt | Weiter >

2.2.3 The Joy of Regular Expressions

The substitution command really becomes powerful when you start using reg- ular expressions. Our examples so far have only had plain alphanumeric charac- ters between the slashes of the substitution. But other characters take on special meanings inside the search and replace strings. Table 2.1 shows just a few.

From this small collection we can do some useful things. We show just a few in Table 2.2. All commands begin with :1,$ to say that the substitution will be attempted from the first through the last line of the file.3 You could use a smaller range for any of these substitutions, as we discussed above.


Table 2.1 Regular expression character meanings


image

image

Character


^

$

.

*

+ []


&

Meaning

The beginning of the line. The end of the line.

Any single character.

Zero or more repetitions of the previous expression. One or more repetitions of the previous expression.

Any of the characters inside the brackets will match—e.g., [abc] matches any of a, b, c. Ranges are allowed too—e.g., [a-z].

When used on the right-hand side, stands for whatever was found with the search string on the left-hand side (for an example, see Table 2.2).


image



image

3. Note that % is valid substitute for 1,$.


Table 2.2 Some useful vi substitutions


image

Command


image

:1,$s/ *$//


:1,$s/^.*$/""/

:1,$s/^"//

:1,$s/"$//

Explanation

Removes all (any number of) trailing blanks—that is, looks for zero or more blanks followed immediately by the end of line, and replaces them with nothing (no characters between the last two slashes).

Puts quotes around the text of each and every line.

Removes the leading quote from any line that starts with one. Removes the trailing quote from any line that ends with one.

image


There is so much more that could be said about regular expressions. They are one of the most powerful features for making big changes with few keystrokes. It’s an integral part of sed, Perl, and other tools. It’s in such demand that it has been added to Java for better pattern matching. See Section 2.6 for ways to learn more about regular expressions.