Pattern-Matching Rules

In making global replacements, Unix editors such as vi allow you to search not just for fixed strings of characters, but also for variable patterns of words, referred to as regular expressions.

When you specify a literal string of characters, the search might turn up other occurrences that you didn’t want to match. The problem with searching for words in a file is that a word can be used in different ways. Regular expressions help you conduct a search for words in context. Note that regular expressions can be used with the vi search commands / and ?, as well as in the ex commands :g and :s.

For the most part, the same regular expressions work with other Unix programs, such as grep, sed, and awk.[21]

Regular expressions are made up by combining normal characters with a number of special characters called metacharacters.[22] The metacharacters and their uses are listed next.

Metacharacters Used in Search Patterns

. (period, dot)

Matches any single character except a newline. Remember that spaces are treated as characters. For example, p.p matches character strings such as pep, pip, and pcp.

*

Matches zero or more (as many as there are) of the single character that immediately precedes it. For example, bugs* will match bugs (one s) or bug (no s). (It will also match bugss, bugsss, and so on.)

The * can follow a metacharacter. For example, since . (dot) means any character, .* means “match any number of any character.”

Here’s a specific example of this: the command ...

Get Learning the vi and Vim Editors, 7th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.