Koke’s

My English alter-ego

Function of the day: rgrep

Posted by Jorge Bernal May 08, 2008

Updated: I’ve added some –exclude options to ignore svn and git directories. Also be sure to check out the comments, there are pretty nice variations there.

Add this to your ~/.bashrc

rgrep () { grep -rin --exclude=\*.svn\* --exclude=\*.git\* "$*" . }

And you get a handy grep replacement

$ rgrep function wp_head ./general-template.php:785:function wp_head() {

Bookmark this post: · Del.icio.us · YahooMyWeb · Spurl · Furl · Incoming links

AddThis Social Bookmark Button   AddThis Feed Button

6 Responses to “Function of the day: rgrep”

Comments

  1. hads May 08 2008 / 11am

    I like to throw and -I in there as well which is useful when grepping against directories with binaries in it.

  2. salty-horse May 08 2008 / 3pm

    Have you tried ack?

    It’s designed to replace most of grep’s usecases.
    It can search recursively in source code files, skipping directories like .svn.

    You’ll never need to hack grep scripts again :)

  3. Tormod May 08 2008 / 4pm

    The name rgrep is already used by /usr/bin/rgrep. You can also use an alias, which has a few advantages:
    alias grepr=”grep -rin”

  4. Wael Nasreddine May 08 2008 / 7pm

    There’s always the perl script rgrep with prunes support… here’s the script copied from here

    #!/usr/bin/perl -w
    #
    # vim:ft=perl:fenc=UTF-8:ts=4:sts=4:sw=4:expandtab:foldmethod=marker:foldlevel=0:
    #
    # $Id$
    #
    # originally by Michael Schwern

    # Like grep -r except…
    # * you can leave off the directory and it will use . instead of waiting like
    # a dumbshit for STDIN
    # * It handles paths with spaces and quotes.
    # * it will not traverse into these directories or files.
    my @Prunes = (qw(.svn CVS blib *~ *.bak _darcs imap_cachedir), ‘#*’);

    my @Args = @ARGV;
    my $Dir;
    if( grep(!/^-/, @Args) <= 1 ) {
    $Dir = ‘.’;
    }
    else {
    $Dir = pop @Args;
    }

    @Args = map { “‘$_’” }
    map { s/’/'”‘”‘/g; $_ } @Args;

    # Escape spaces and quotes
    $Dir =~ s{([ ‘”])}{\\$1}g;

    my $prunes = join ‘ -o ‘, map { “-name ‘$_’ -prune” } @Prunes;
    exec “find $Dir $prunes -o -type f -print0 | “.
    “xargs -0 grep –color=auto @Args”;

  5. Ilmari Vacklin May 08 2008 / 9pm

    I also recommend ack (see ).

  6. Alexandre May 10 2008 / 7pm

    Your post makes me remember of my short helper that I uses all the time:


    rg()
    {
    filepat="$1"
    pat="$2"
    shift 2
    grep -Er --include=$filepat $pat ${@:-.}
    }
    # In Zsh, 'noglob' turns off globing.
    # (e.g, "noglob echo *" outputs "*")
    alias rg='noglob rg'

    It is lovely to use:


    % rg *.c ^PyErr Lib/
    % rg *.c PyErr_Restore . -C 10 | less
    % rg *.[ch] stringlib
    % rg *.c ^[a-zA-Z]*_dealloc Modules/ Objects/

Leave a Reply