Find and Replace in Vim Without Plugins

Find and replace across files is one of those features I frequently see Vim users reverting back to something like Sublime or another more GUI driven editor. This apparent weakness in Vim bothered me so I went in search of how to find and replace across multiple files or directories in a project without leaving Vim.

It turns out there are built in building blocks we can use to build up this command. It’s not as easy as command+f in some other editors but it is powerful and allows you to stay in your Vim bliss without installing additional plugins.

Let’s say we have a project with three files discussing our new inventions where we managed to typo the word “inventions” as “inventoin”.

$ touch foo.txt bar.txt baz.txt
$ echo My first inventoin > foo.txt
$ echo My groundbreaking inventoin > bar.txt
$ echo My next inventoin > baz.txt

We’ll open up Vim:

$ vim .

and use the :arg command to glob for all the .txt files in our project.

:arg *.txt

We can then use the :args command to see which files were found.

:args

The result is:

[bar.rb] baz.rb foo.rb

Since we’re happy with the files within which we want to search we can now issue the find and replace command.

:argdo %s/inventoin/invention/cge | update

There are a few ideas to unpack here. We are saying run (do) this command against all the files we found previously (arg). The specific command does the following things:

And voilĂ , find and replace across directories within Vim and without plugins.

New to Vim? See this intro post for some beginner tips.