Vim’s search and replace feature is powerful. It allows you to search for patterns with regular expressions.
Use the manual’s entry via
:h pattern-searches for the help menu.
The basic usage for search in normal mode is
/ followed by the pattern for a forward search, and
? followed by a pattern for a backwards search.
Search and replace:
:s/<pattern to replace>/<replacement>/<flags>
Search and replace in file:
:%s/<pattern to replace>/<replacement>/<flags>
Below are useful tricks I found that may not be obvious to a casual Vim user.
Replace Command Separators⌗
You can change the separators between different commands. That’s useful if you want to replace something with forward slashes.
You want to replace
github.com/my-username in the complete file.
Notice how you need to escape the slashes with a backslash.
Instead you can do this:
I didn’t find this gem in the documentation, but came upon this idea by borrowing how the sed utility does it. Turns out, Vim can do that, too.
Let’s say you want to replace something with an uppercase word but can’t be bothered to type your replacement string in uppercase.
Let’s replace all
\U transforms all following characters into uppercase.
Fine-Grained Control with the
You can separate the match from the substitution:
Translation: for every line containing “foo” substitute all “bar” with “zzz.”
Use the Argument List to Search and Replace in Multiple Files⌗
:args command to collect a list of files which match a pattern.
For example, find all files that contain the string
args `grep -l github`
Then open the argument list with
Run search and replace with