How to be a better grepper

28 April, 2009 - 17:37
Categories:

If you're not afraid of a a bit o' Unix/Linux/OSX command line delight, you're probably having grep hanging on your tool belt.

One option you'll wonder how you could live without is --color, which enables highlighting of the word or pattern you are grepping for. I find it so useful that I've put the following alias in my .bashrc:

alias grep='grep --color=auto'

Another useful trick when you're working on version controlled source code (with Subversion for example) is disabling the recursive walk through the .svn directories. For this I have the following in my .bashrc:

# Exclude grepping through .svn folders.
GREP_OPTIONS="--exclude-dir=\.svn"
export GREP_OPTIONS

If the above makes you scream "good heavens, I wish I knew this decades ago", you should also consider the grep-killer ack, which offers the above (and many more) by default.

2 May, 2009 - 18:23

"good heavens, I wish I knew this decades ago" :-)

Jo Wouters (not verified)

I never knew there was a '--color' option with grep; so I generally piped my grep to a file, to open in with vim or less and highlight the word pattern I was looking for.

To exclude 'svn', I generally pipe the output of my grep through another one, excluding all lines with 'svn' in. (ex: grep -ir 'searching123' . | grep -v svn)
Your solution is faster, more elegant and gives different (read: correct) compared to the way I did this.

So: "good heavens, I wish I knew this decades ago" :-)

6 May, 2009 - 11:19

fgrep and egrep

Rob Syme (not verified)

Thanks for the post. In changing my .bashrc, I came across a logical extension.
If you're in the habit of using fgrep and egrep, you might want to expand the .bashrc addition to something like:

if [ -x /usr/bin/dircolors ]; then
  alias grep='grep --color=auto'
  alias fgrep='fgrep --color=auto'
  alias egrep='egrep --color=auto'
fi

Ripped from Ubuntu's .bashrc - not my own idea.

-r

Post new comment

The content of this field is kept private and will not be shown publicly.
  • No HTML tags allowed
  • Lines and paragraphs break automatically.

More information about formatting options