Last Updated: October 12, 2018
· underhilllabs

Vim: Edit Files that Grep finds

Okay so there are a series of files that need to be updated and fixed. You can grep the evil pattern and then send the list of files affected to vim for a quick fix.

Use Grep to find files and pass to Vim

grep -l "messed up pattern" */*| vim -

grep -l <pattern> /

this searches for the pattern and lists (-l) the files affected

| vim -

the output of grep is sent to a vim buffer

Open each file individually with gf (option a)

  1. First must run :set hidden to allow buffer with file names to be buried
  2. Next put cursor over filename and type gf. Vim will open that file in a new buffer.
  3. When you are finished editing file, type C-o to return to file list.

Run :bufdo %s/// to updated all files at once (option b)

You first must run :set hidden to allow the buffer with file names to be buried

:bufdo %s/messed up pattern/good happy sub/ge | update

  • bufdo runs a command on all open buffers.
  • %s/old/new/ge is the substitution command bufdo will run on all buffers.
  • | update will write the changes to all buffers that have changed.

all done!

8 Responses
Add your response

oelmekki, that's definitely an improvement! I was using this grep/vim combination this week for specific case, but using "-r" would make it a lot more general.

over 1 year ago ·

Or alternatively could use ack, as it's a whole lot better than grep (

ack -l "pattern" | vim -
over 1 year ago ·

:grep "pattern" in vim is even better - loads into the quickfix window, etc.
:set grepprg='ag' for even faster searching

over 1 year ago ·

Instead of launching n instances of Vim it could be more productive to edit multiple files in a single one:

ack -l 'pattern' | xargs vim

Then in Vim, use :n to switch to the next file.

over 1 year ago ·

prognostikos, great idea! then you could flip through back and forth through the files with :cnext and :cprev. I knew there was a way to do this internally to vim, but my current working directory is always something else when I think to try the internal grep.

over 1 year ago ·

You know whats even faster, searching through files that are already indexed!

git grep -l 'pattern' | xargs vim
over 1 year ago ·

Or alternatively you can use the Silver Searcher (ag), which is even faster than Ack!

over 1 year ago ·