Introduction
Before we start talking about find and replace in Vim / Vi, let's briefly understand-What is Vim ?
Vim is a free and open-source, screen-based text editor program. The most widely used command-line text editor is Vim. On macOS and the majority of Linux distributions, it is preinstalled. In Vim, finding and replacing text is fast and simple.
In this tutorial, we will show how to find and replace text in Vim/Vi. We will also address a few FAQs on find and replace in Vim / Vi.
Basic Find and Replace
The :substitute (:s)
command in Vim allows you to find and replace text.
You must be in normal mode, which is the editor's default mode, in order to run the commands. Simply hit the "Esc" key to return from any other mode to regular mode.
The substitute command has the following general form:
:[range]s/{pattern}/{string}/[flags] [count]
The command looks for a "{pattern}"
on each line in [range]
and replaces it with a {string}
. The instruction is multiplied by a positive integer called [count]
.
Only the pattern detected in the current line is substituted if neither [range]
nor [count]
are specified. The line where the cursor is placed is the current line.
For instance, you may use the following syntax to find the first instance of the string "foo" in the current line and replace it with "bar":
:s/foo/bar/
Add the g
flag to replace any instances of the search pattern in the current line:
:s/foo/bar/g
Use the percentage character %
as a range, if you wish to search for and replace the pattern throughout the whole file. This character designates a range from the file's first to the final line:
:%s/foo/bar/g
The matched pattern is removed if the {string}
portion is absent and is treated as an empty string. The command "foo" will remove every occurrence of that text in the current line:
:s/foo//g
Any other non-alphanumeric single-byte character than a slash (/)
may be used as a delimiter. When the '/' character appears in the search pattern or the replacement string, you should choose this option.
:s|foo|bar|
Use the c
flag to confirm each substitution:
:s/foo/bar/gc
Output
replace with bar (y/n/a/q/l/^E/^Y)?
If you want to replace the match, then press y
and press l
if you want to replace the match and quit. To stop substitution, use q
or Esc
, or press n
to skip the match. The match and all subsequent instances of the match are replaced by an option. Use CTRL+Y
to scroll the screen down, and CTRL+E
scroll it up.
Regular expressions provide an additional search pattern option. The following command changes all lines beginning with "foo" to "Vim is the best":
Output
:%s/^foo.*/Vim is the best/gc
A line's first character is represented by the ^
sign and any number of characters are represented by the .*
symbol.
Case Sensitivity
Because the case is taken into account by default, searching for "FOO" will not return results for "Foo."
Use the i
flag to disregard the case for the search pattern:
:s/Foo/bar/gi
Add \c
after the search pattern as another approach to forcefully disregard the case. For instance, /Linux\c
does a case-ignorance search.
Use the I
flag to execute a case-sensitive search if you modified the default case setting:
:s/foo/bar/gi
After the pattern, uppercase "\C"
triggers a case-match search as well.
Search Range
In the absence of a range specification, the replace command simply affects the current line.
A single line or a space between two lines might represent the range. The ,
or ;
letters are used to separate the line specifiers. The absolute line number or special symbols may be used to specify the range.
For instance, you might use the following syntax to change every instance of "foo" to "bar" on every line from line 3 to line 10:
:3,10s/foo/bar/g
The first and final lines are included in the range since it is inclusive.
The dollar symbol ($)
and the dot (.)
characters denote the first and final lines, respectively. From the current line to the last, replace "bar" with "foo":
:.,$s/foo/bar/
The "+" or "-" sign, followed by a number that is added to or removed from the line number before it, may also be used to specify a line. If the number is left out after the sign, it defaults to 1.
For instance, enter the following to replace every "foo" on the current line and the four next lines with "bar":
:.,+4s/foo/bar/g
Substituting Whole Word
Instead of searching for a single word, the replace command searches for the pattern as a string. For instance, if you searched for "gnu," the search would turn up results where "gnu" was nested inside of longer terms like "cygnus" or "magnum."
To search for a whole word, to mark the beginning of a word type \<
, enter the search pattern, to mark the end of the word type \>
:
For example, to search for the word “foo” you would use \<foo\>
:
:s/\<foo\>/bar/
Substitute History
Vim records every command you issue during the current session. Enter :s
and the arrow up/down keys may be used to locate a prior substitution operation in the history of substitute instructions. Simply hit Enter
to execute the command. Before acting, you may modify the command.
Examples
Comment lines from 5 to 20 (include a #
before the line):
:5,20s/^/#/
Comment out lines 5 through 20, and undo the prior modifications:
:5,20s/^#//
Change all occurrences of "apple," "orange," and "mango" to "fruit":
:%s/apple\|orange\|mango/fruit/g
At the end of each line, eliminate any trailing whitespace:
:%s/\s\+$//e
FAQs on Find and Replace in Vim/Vi
How do you enter search mode in Vim/Vi?
To enter search mode, press the /
key followed by the search pattern. For example, /search_pattern
.
How can I search for a specific word in Vim/Vi?
To search for a specific word, enter it after the /
in search mode. For example, /word
will find the first occurrence of "word".
Can I search for a pattern and replace it with new content in Vim/Vi?
Yes, you can use the :s
command to find and replace text in Vim/Vi. For example, :%s/pattern/replacement
replaces the first occurrence of "pattern" with "replacement" on all lines.
How do I replace all occurrences of a pattern on a single line in Vim/Vi?
Use :s/pattern/replacement/g
to replace all occurrences of "pattern" with "replacement" on the current line.
How can I replace all occurrences of a pattern in the entire file in Vim/Vi?
To replace all occurrences of a pattern in the entire file, use :%s/pattern/replacement/g
.
Can I confirm each replacement in Vim/Vi?
Yes, you can use :%s/pattern/replacement/gc
to replace all occurrences of "pattern" with "replacement" and confirm each replacement individually.
Can I find and replace interactively in Vim/Vi?
Yes, you can use Vim/Vi's interactive mode by prefixing the :s
command with c
. For example, :%s/pattern/replacement/gc
prompts for each replacement.
Conclusion
Vim's excellent searching and replacing functionality makes it simple to swiftly edit your text.
If you have any queries, please leave a comment below and we’ll be happy to respond to them.