Pattern-Matching Examples
Unless you are already familiar with regular expressions, the preceding discussion of special characters probably looks forbiddingly complex. A few more examples should make things clearer. In the examples that follow, a square (□) is used to mark a space; it is not a special character.
Let’s work through how you might use some special characters in
a replacement. Suppose that you have a long file and that you want to
substitute the word child with the word
children throughout that file. You first save the
edited buffer with :w
, then try the
global replacement:
:%s/child/children/g
When you continue editing, you notice occurrences of words such
as childrenish. You have unintentionally matched
the word childish. Returning to the last saved
buffer with :e!
, you now
try:
:%s/child□/children□/g
(Note that there is a space after child.) But this command misses the occurrences child., child,, child: and so on. After some thought, you remember that brackets allow you to specify one character from among a list, so you realize a solution:
:%s/child[□,.;:!?]/children[□,.;:!?]/g
This searches for child followed by either
a space (indicated by □) or any one of the punctuation characters
,.;:!?
. You expect to replace this
with children followed by the corresponding space
or punctuation mark, but you’ve ended up with a bunch of punctuation marks after every occurrence
of children. You need to save the space and
punctuation marks inside a \(
and
\)
. Then you can “replay” them ...
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.