6.4. Pattern-Matching Examples

Unless you are already familiar with regular expressions, the discussion of special characters above 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[ ...

Get Learning the vi Editor, Sixth 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.