Search & Replace

In the searching we learned how to search for text in a buffer. Later, we learned how to expand our search capabilities with patterns in order to more precisely target the words and patterns we wanted to search for.

In this chapter we learn how to extend this capability even further, with substitutions.

The substitute command (typically abbreviated to simply s, as shown below) is used to execute search and replace operations in Vim. This command's call signature is:




Range is an optional range as described in detail in the ranges section. If omitted, the search and replace will take place over the current line. To apply the search and replace operation over the current buffer, use the range %.


is the pattern to search for. If the search pattern is omitted, then the last search pattern is used.


is the content to replace matched text with. If replace is omitted then matched text is replaced with an empty string, thus deleting it.

The replacement text can include several types of content, which are discussed in the following sections:

String Literals
Text can be replaced with literal strings
The replacement text can contain back-references, so that the replacement string contains content extracted from capturing groups in the search pattern.
When {replace} starts with = it is evaluated as an expression, which provides additional flexibility


Several flags are available to control the behavior of the how each search is executed, and are discussed next.