Cover by Arnold Robbins

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Substitution and Regular Expressions

Regular expressions, and their use with the substitute command, are what give vi most of its significant editing power.

The Substitute Command

The general form of the substitute command is:

:[addr1[,addr2]]s/old/new/[flags]

Omitting the search pattern (:s//replacement/) uses the last search or substitution regular expression.

An empty replacement part (:s/pattern//) “replaces” the matched text with nothing, effectively deleting it from the line.

Substitution flags

Flag

Meaning

c

Confirm each substitution

g

Change all occurrences of old to new on each line (globally)

p

Print the line after the change is made

It’s often useful to combine the substitute command with the ex global command, :g:

:g/Object Oriented/s//Buzzword compliant/g

vi Regular Expressions

.

(period) Matches any single character except a newline. Remember that spaces are treated as characters.

*

Matches zero or more (as many as there are) of the single character that immediately precedes it.

The * can follow a metacharacter, such as ., or a range in brackets.

^

When used at the start of a regular expression, ^ requires that the following regular expression be found at the beginning of the line. When not at the beginning of a regular expression, ^ stands for itself.

$

When used at the end of a regular expression, $ requires that the preceding regular expression be found at the end of the line. When not at the end of a regular expression, $ stands for itself.

\

Treats the following special character ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required