Opening the results of a grep in Vim

This week while removing some deprecated syntax from our old tests I found myself wondering how to take the results of my grep command and open the files returned in vim. Moments like this are great for getting to know your tools better so I decided to figure it out. Opening the files was not that difficult to figure out:

vim -o `grep -ril Factory.build test/`

This did exactly the right thing, a case insensitive (-i), recursive (-r) search of the test directory for the problematic syntax (Factory.build) returning only filenames (-l) and then opening the results in vim. I was able to quickly make my changes with a search and replace. With that done you can then write all buffers and close vim with:

:xa

I really love finding stuff like that. While that solved the immediate need, as written, it would not be able to deal with file names that have spaces in them. Since that sort of thing bugs me, I set up some test files and gave it a try:

mike@sleepycat:~/projects/vimtest☺  tail ./*
==> ./fileone <==
blah
blah
cats
blah

==> ./filethree <==
blah
rabbits
blah

==> ./file two <==
blah
racoons
dogs and cats
blah

After a little tinkering I figured it out with a little help from the xargs man page. Its not something I would want to type often but this will make a very useful alias or script some time:

grep -Zril cats . | xargs -0 sh -c 'vim -O "$@" < /dev/tty' vim

Advertisements

1 thought on “Opening the results of a grep in Vim”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s