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.
Example:
You want to replace github.com/my-username
in the complete file.
:%s/github.com\/my-username/gitlab.com\/my-other-username/g
Notice how you need to escape the slashes with a backslash.
Instead you can do this:
:%s_github.com/my-username_gitlab.com/my-other-username_g
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.
Further Reading:
Changing Case
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 github
with GITLAB
:
:%s/github/\Ugitlab/g
\U
transforms all following characters into uppercase.
See :h sub-replace-special
.
Source: Changing case with regular expressions
Fine-Grained Control with the global
Flag
You can separate the match from the substitution:
:% g/foo/s/bar/zzz/g
Translation: for every line containing “foo” substitute all “bar” with “zzz.”
Source: Your problem with Vim is that you don’t grok vi.
Use the Argument List to Search and Replace in Multiple Files
Use the :args
command to collect a list of files which match a pattern.
For example, find all files that contain the string github
:
args `grep -l github`
Then open the argument list with :args
again.
Run search and replace with :argdo
:
:argo %s/github/GitHub/g
Source: Vim search replace all files in current (project) folder