Search code examples
grepack

How do you configure grep to act more like ack?


How would you get grep to exclude the files that ack excludes (temp files and version control directories) without typing out the exclude patterns?

As described here, you could use GREP_OPTIONS, but then you run into the problems here: scripts that use grep without clearing GREP_OPTIONS will break.

What is the better way? An alias? Or another script that wraps grep?

While the obvious answer is alias grep="ack -a", I'm academically interested in how to solve this problem without using ack.


Solution

  • My current solution is to use an alias to restrict the use of my smart options to my interactive inputs (and not other people's scripts). This is the grep-relevant snippet from my bash_aliases:

    SMART_GREP_OPTIONS=
    
    # Ensure colors are supported.
    if [ -x /usr/bin/dircolors ]; then
        SMART_GREP_OPTIONS=' --color=auto'
    fi
    
    
    # Make grep more like ack.
    #   Ignore binary files.
    SMART_GREP_OPTIONS="$SMART_GREP_OPTIONS --binary-files=without-match"
    # Check for exclude-dir to prevent invalid options in older versions of grep.
    # Assume if we have exclude-dir, that we have exclude.
    if /bin/grep --help | /bin/grep -- --exclude-dir &>/dev/null; then
        # Ignore version control folders.
        for PATTERN in .cvs .git .hg .svn; do
            SMART_GREP_OPTIONS="$SMART_GREP_OPTIONS --exclude-dir=$PATTERN"
        done
        # Ignore temp files.
        for PATTERN in *.swp; do
            SMART_GREP_OPTIONS="$SMART_GREP_OPTIONS --exclude=$PATTERN"
        done
    fi
    # This alias may override ghostscript. That's not a problem for me.
    alias gs='grep $SMART_GREP_OPTIONS'
    

    I do most of my grepping from vim and use vim-searchsavvy to setup similar options (I don't use my alias from vim).