vi Tips and Tricks
The best way to learn pattern matching is by example,
so here's a short list of pattern-matching examples, with explanations.
has a list of these patterns.)
Study the syntax carefully so you understand the principles at work.
You should then be able to adapt these examples to your own situation.
Change all occurrences of the word help
) to HELP
changes the pattern that follows to all uppercase. The
pattern that follows is the repeated search pattern, which is
Replace one or more spaces following a colon (
) or a period
) with two spaces (here a space is marked by a \h'1p'\h'1p'):
Either of the two characters within brackets can be matched.
This character is saved into a
hold buffer, using
and restored on the right-hand side by the
Note that within brackets a special character such as a dot
does not need to be escaped with a backslash (
Delete all blank lines:
What you are actually matching here is the beginning of the line (
followed by the end of the line (
), with nothing in between.
Delete all blank lines, plus any lines that contain only white space:
(In the line above, a tab is shown as
A line may appear to be blank but may in fact contain spaces or tabs.
The previous example will not delete such a line.
This example, like the one above it, searches for the beginning and end
of the line. But instead of having nothing in between, the
pattern tries to find any number of spaces or tabs.
If no spaces or tabs are matched, the line is blank.
To delete lines that contain white space but that aren't
you would have to match lines with at least
one space or tab:
Match the first quoted argument of all section header (
replace each line with this argument:
:%s/^\.Ah "\([^"]*\)" .*/\1/
The substitution assumes that the
macro can have more than
one argument surrounded by quotes. You want to match everything
between quotes, but only up to the first
closing quote. Using
would be wrong because it would match all arguments
on the line. What you do is match a series of characters that
. The pattern
matches a quote, followed by any number of
non-quote characters, followed by a quote. Enclose the first argument
so that it can be replayed using
Same as previous, except preserve the original lines by copying them:
:g/^\.Ah/t$ | s/\.Ah "\([^"]*\)" .*/\1/
, the vertical bar (
) is a command separator
that works like a
on a UNIX command line. The first part,
matches all lines that begin with a
macro, uses the
command to copy these lines, and places them after the last
) of the file. The second part is the same as in
the previous example, except that the substitutions are performed on
copies at the end of the file. The original lines are unchanged.
- from O'Reilly & Associates' Learning the vi Editor
, Chapter 6