Replacing all occurrences in a file
Say you need to rename a variable that occurs multiple times in a file. How to do that?
:help substitute) is a very simple yet powerful way to replace one string with another.
Say, you need to replace the word "complicated" with "simple".
Note that this command only applied to the current line, but you can also specify a range:
This command will work for every line from 1 to 20. Or we could use
to use it on all lines in the file.
g flag at the end means "global" (replaces all occurrences instead of just the first one in each line).
Other useful flags include
i (ignore case), or
p (print the last line). See
:help s_flags for more.
Another nice trick with substitute is that it build on regular search with
You could start with a simple search
/complicated. You might wanna look around, make sure that you want to replace all of those occurrences.
Then, you just type
%s//simple/g. No need to type the search pattern again, it will just use your last search. Neat, right?
:help substitute— start here
- Vim and Language Server Protocol — semantics-aware language servers do even better job replacing symbols.