A Final Look at Pattern Matching

We conclude this chapter by presenting sample tasks that involve complex pattern-matching concepts. Rather than solve the problems right away, we’ll work toward the solutions step by step.

Deleting an Unknown Block of Text

Suppose you have a few lines with this general form:

the best of times; the worst of times:  moving
The coolest of times; the worst of times:  moving

The lines that you’re concerned with always end with moving, but you never know what the first two words might be. You want to change any line that ends with moving to read:

The greatest of times; the worst of times:  moving

Since the changes must occur on certain lines, you need to specify a context-sensitive global replacement. Using :g/moving$/ will match lines that end with moving. Next, you realize that your search pattern could be any number of any character, so the metacharacters .* come to mind. But these will match the whole line unless you somehow restrict the match. Here’s your first attempt:

:g/moving$/s/.*of/Thegreatestof/

This search string, you decide, will match from the beginning of the line to the first of. Since you needed to specify the word of to restrict the search, you simply repeat it in the replacement. Here’s the resulting line:

The greatest of times:  moving

Something went wrong. The replacement gobbled the line up to the second of instead of the first. Here’s why: when given a choice, the action of “match any number of any character” will match as much text as possible ...

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.