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 |
---|---|
| Confirm each substitution |
| Change all occurrences of old to new on each line (globally) |
| 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 ...
Get vi and Vim Editors Pocket Reference, 2nd 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.