sponsor Vim development Vim logo Vim Book Ad

basic Tip #1392: Shell script to use grep with gvim

 tip karma   Rating 32/25, Viewed by 2489 

Read and edit this tip on the Vim tip wiki. The wiki may have a more recent version of this tip.

created:   November 21, 2006 5:09      complexity:   basic
author:   Mauro      as of Vim:   6.0

With bash or ksh add on .bashrc or on .kshrc:
function vimgrep
{
vimgrep_temp_file=/tmp/vimgrep_$$.tmp
  find . \( -name "*.cc"  -o -name "*.h" -o -name "*.i" -o -name "*.icc" \) -print -follow | grep -v "CVS/" | sed "s/ /\\\/g" | xargs egrep -H -n -e $* > $vimgrep_temp_file
gvim -q $vimgrep_temp_file -c copen
rm  $vimgrep_temp_file
}
and type from shell:
$ vimgrep searchstring
In vim you can set grepprg to vimgrep:
:set grepprg=vimgrep





 rate this tip  Life Changing Helpful Unfulfilling 

<< Disable match paren restriction (visible lines -> whole file) | Automatically create/set tmp or backup directories >>

Additional Notes

Anonymous, November 21, 2006 5:19
fix:
In vim set grepprg=vimgrep where vimgrep is:
  find . \( -name "*.cc"  -o -name "*.h" -o -name "*.i" -o -name "*.icc" \) -print -follow | grep -v "CVS/" | sed "s/ /\\\/g" | xargs egrep -H -n -e
Anonymous, November 21, 2006 7:52
Why not use the built-in :vimgrep command?
[email protected], November 21, 2006 8:24
Yes It's correct anyway If we want to grep recursively all the *.cc *.h *.i we have to redefine the grepprg corectly
nash at nash id au, December 4, 2006 17:16
If your shell is zsh, or another that supports similar extended globbing you can just use:
:grep foo **/*.c
to do pretty much the same thing.

http://www.staniford.net, January 22, 2007 3:46
Hi,

I did something very similar to this a while ago, and I agree it's very useful to do this from the shell.  However,
because I use it in all kinds of ways, I prefer to just have the shell script vimgrep emulate grep exactly.  So that I can do:

find /etc | xargs vimgrep userid (for example)

So my vimgrep shell script behaves just like grep does and takes all greps args.  It also doesn't bother starting vim if grep returns zero matches...

#!/bin/bash

date=`date +%s`;
grep -n "$@" > /tmp/grep-$date
fs=`du -b /tmp/grep-$date | cut -f1`
if [ $fs -gt 0 ]
then
        gvim -q /tmp/grep-$date
fi
rm /tmp/grep-$date
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to the maillist. Help Bram help Uganda.
   
Sponsored by Web Concept Group Inc. SourceForge.net Logo