Find and Replace in Multiple Files

Most times a language server will do the heavy lifting for you when renaming things like variables or functions, but sometimes you are just dealing with plain text.

Unavoidably, there comes a moment in every developer’s life where a find and replace across multiple files is needed. I remember first learning about find and replace from a colleague — it felt like powerful black magic. However, it can also be quite a harrowing experience. For example, the day after learning about it, I used it to update some copy but accidentally renamed many variables and functions.

git add .
git commit -m "Align terminology throughout copy"
git push

Of course, it was a Friday and the last thing I did before leaving the office.

Find and replace is undoubtedly a super useful tool to have in your metaphorical toolbox, but it must be used responsibly, especially in larger projects. Let’s learn how to do just that using Neovim .

Find

To search for our keyword or regular expression , we will use the built-in command vimgrep and then open the results in the quickfix list. Imagine we want to find all occurrences of “hello” in files located within the ./src/ folder.

:vimgrep /hello/j src/**/*

Here’s a quick breakdown of the command above:

  • : puts Vim in command mode.
  • vimgrep is the search tool built into Vim.
  • /hello/j is our search pattern. The j flag is optional and specific to vimgrep; it prevents jumping to the first result found.
  • src/**/* means any file in any folder inside src/.

There are plugins you could use, like Telescope  or Spectre , to make the process a bit more user-friendly. Any result is output to the quickfix list.

:copen

and Replace

The substitute  command, s, handles replacements. To replace “hello” with “world” in a controlled fashion we can append the confirmation flag c.

:cdo s/hello/world/c

cdo runs the substitution for every result in the quickfix list. Check each replacement carefully and apply with y, or leave unchanged with n.

Happy coding!