Alex Rivera | Logout

Search and replace in Vim across all the project files

Asked 2011-01-26T12:10:24.633
141

I'm looking for the best way to do search-and-replace (with confirmation) across all project files in Vim. By "project files" I mean files in the current directory, some of which do not have to be open.

One way to do this could be to simply open all of the files in the current directory:

:args ./**

and then do the search and replace on all open files:

:argdo %s/Search/Replace/gce

However, when I do this, Vim's memory usage jumps from a couple dozen of MB to over 2 GB, which doesn't work for me.

I also have the EasyGrep plugin installed, but it almost never works—either it doesn't find all the occurrences, or it just hangs until I press CtrlC. So far my preferred way to accomplish this task it to ack-grep for the search term, using it's quickfix window open any file that contains the term and was not opened before, and finally :bufdo %s/Search/Replace/gce.

I'm looking either for a good, working plugin that can be used for this, or alternatively a command/sequence of commands that would be easier than the one I'm using now.

Edit
Report

1 Answer

25

maybe do this:

:noautocmd vim /Search/ **/*
:set hidden
:cfirst
qa
:%s//Replace/gce
:cnf
q
1000@a
:wa

Explanation:

  • :noautocmd vim /Search/ **/* ⇒ lookup (vim is an abbreviation for vimgrep) pattern in all files in all subdirectories of the cwd without triggering autocmds (:noautocmd), for speed's sake.
  • :set hidden ⇒ allow having modified buffers not displayed in a window (could be in your vimrc)
  • :cfirst ⇒ jump to first search result
  • qa ⇒ start recording a macro into register a
  • :%s//Replace/gce ⇒ replace all occurrences of the last search pattern (still /Search/ at that time) with Replace:
    • several times on a same line (g flag)
    • with user confirmation (c flag)
    • without error if no pattern found (e flag)
  • :cnf ⇒ jump to next file in the list created by the vim command
  • q ⇒ stop recording macro
  • 1000@a ⇒ play macro stored in register a 1000 times
  • :wa ⇒ save all modified buffers

* EDIT * Vim 8 way:

Starting with Vim 8 there is a better way to do it, as :cfdo iterates on all files in the quickfix list:

:noautocmd vim /Search/ **/*
:set hidden
:cfdo %s//Replace/gce
:wa
answered 2011-01-26T12:17:37.130

Your Answer