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)
- First must run
:set hidden
to allow buffer with file names to be buried - Next put cursor over filename and type
gf
. Vim will open that file in a new buffer. - 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!
Written by Bart Lantz
Related protips
8 Responses
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.
Or alternatively could use ack, as it's a whole lot better than grep (http://betterthangrep.com/):
ack -l "pattern" | vim -
:grep "pattern"
in vim is even better - loads into the quickfix window, etc.
:set grepprg='ag'
for even faster searching
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.
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.
yeah, there's also this:
You know whats even faster, searching through files that are already indexed!
git grep -l 'pattern' | xargs vim
Or alternatively you can use the Silver Searcher (ag), which is even faster than Ack!