Replacing all occurrences in a file

March 10, 2021

Say you need to rename a variable that occurs multiple times in a file. How to do that?

Substitute (: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".

:s/complicated/simple/g

Note that this command only applied to the current line, but you can also specify a range:

:1,20s/complicated/simple/g

This command will work for every line from 1 to 20. Or we could use

:%s/complicated/simple/g

to use it on all lines in the file.

The 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?

What's next?

Vim For Developers

Vim For Developers

❄️ 35% off this Christmas season! ❄️

Learn Vim and upgrade your productivity to the next level by building the IDE of your dreams.

LEARN MORE