It is a common task to search and replace all occurrences of a word within the current buffer.
For example, given the following buffer :
Initial Conditions
Beautiful·is·better·than·ugly.
Explicit·is·better·than·implicit.
Simple·is·better·than·complex.
Complex·is·better·than·complicated.
Flat·is·better·than·nested.
Sparse·is·better·than·dense.
Readability·counts.
COMMAND
Top
1:1
:%s/is/is way/
Suppose one wants to change all occurrences of is better
to is
way better
. The general template for searching and replacing is:
:[range]s/{pattern}/{replacement}/[flags]
where
Template | Value | Description |
---|---|---|
: | Puts Vim into Command Mode | |
[range] | % | Applies this command to the entire file |
s/ | Indicates that this is a search and replace operation | |
{pattern}/ | is | Specifies the pattern to search for |
{replacement}/ | is way | Specifies the text to replace the search pattern with. |
[flags] | No flags are specified. |
Putting this all together and executing the command:
Title
Beautiful·is·way·better·than·ugly.
Explicit·is·way·better·than·implicit.
Simple·is·way·better·than·complex.
Complex·is·way·better·than·complicated.
Flat·is·way·better·than·nested.
Sparse·is·way·better·than·dense.
Readability·counts.
NORMAL
75%
6:1
6 substitutions on 6 lines
As expected, each occurrence of is
has been replaced with is way
.
Writing patterns can sometimes require a bit of trial and error, if the final text is not as expected, simply hit u to return to the original:
Title
u
Beautiful·is·better·than·ugly.
Explicit·is·better·than·implicit.
Simple·is·better·than·complex.
Complex·is·better·than·complicated.
Flat·is·better·than·nested.
Sparse·is·better·than·dense.
Readability·counts.
NORMAL
Top
1:1
6 changes; before #1 0 seconds ago