Search and Replace in Vim
2024-11-29
Search and replace in Vim uses the :s
command to quickly substitute text in a line, range, or entire file. With options like global replacement, word boundaries, and confirmation prompts, it streamlines editing tasks efficiently.
In Vim, you can perform a search and replace using the :s
(substitute) command. Here are a few common ways to do it:
Replace in the current line:
:s/old_text/new_text/g
old_text
: the text you want to replace.new_text
: the text you want to replace it with.g
: makes the substitution "global" for all occurrences in the line. Without it, only the first occurrence will be replaced.
Replace in the entire file:
:%s/old_text/new_text/g
%
: applies the command to every line in the file.
Replace in a specific range of lines:
:5,10s/old_text/new_text/g
5,10
: applies the command to lines 5 through 10.
Confirm each replacement:
:%s/old_text/new_text/gc
c
: asks for confirmation before each replacement. Typey
for "yes,"n
for "no,"a
for "all," orq
to quit.
Replace only whole words:
:%s/\<old_text\>/new_text/g
\<
and\>
match the beginning and end of a word boundary.
This flexibility allows for very precise control over replacements in Vim.