Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace all instances of specific string in multiple files in vim

Tags:

vim

vi

I'm still relatively new to Vim and can't figure out how to replace all instances of a specific string in multiple files (from a specific project directory). Ideally I want to do this without any additional plugins; was looking into :vimgrep and :arg options but can't work it out.

Thanks for your time in advance!

like image 553
John_L_Smith Avatar asked Dec 02 '25 16:12

John_L_Smith


1 Answers

The general workflow is:

  1. Search for your pattern across the project.
  2. Operate on each match (safer, slower) or on each file with matches (riskier, faster).
  3. Write your changes.

The first step can be done with any command that populates the quickfix list: :help :vimgrep, :help :grep, something from a third-party plugin, etc.

Taking :grep as an example:

:grep foo **/*.js

will populate the quickfix list with an entry for every foo found in *.js files in the current directory and subcategories. You can see the list with :cwindow.

The second step involves :help :cdo or :help :cfdo:

:cdo s/foo/bar/gc

which will substitute every foo with bar on each line in the quickfix list and ask for confirmation. With :cfdo it would look like that:

:cfdo %s/foo/bar/gc

If you are super confident, you can drop the c at the end. See :help :s_flags.

The third step involves :help :update:

:cfdo update

which will write every file in the quickfix list to disk if they have been changed.

In short:

:gr foo **/*.js
:cdo s/foo/bar/gc
:cfdo up
like image 190
romainl Avatar answered Dec 04 '25 10:12

romainl