Image by dannyman via Flickr
One of my favorite tools is "grep." That gives away the fact that I spend more time on the command line than many. One of the things I originally loved about OS X was that I could fire up a terminal and use the machine just like Unix (yeah, Linux was a new fangled thing for me).
Recently I complained about always having to look up a certain switch for grep and Weldon Dodd tweeted "if you write a blog post about grep, maybe others will commit the switch to memory too, and when I say others, I mean me." So, here it is.
Grep is an acronym from "global, regular expression, print" three commands you often did in a row inside ed, a primitive Unix editor (vi is slightly better, emacs is the best, of course). As an aside, knowing some rudimentary ed commands is a good thing for any sysadmin because it's always available, even in single-user mode.
Grep is used to searching files. I was using it this morning to search for strings in old email mailboxes to find a Quicktime registration. The fact that grep accepts regular expressions makes it a very powerful tool for finding data in files.
There are only a few flags I commonly use:
- -H - print the filename of any matching files. If you grep a file glob and get match you want to know which file in the glob the match was in
- -P - use Perl-style regular expressions
There are others, just grep --help to see them.
One thing you will commonly want to do is grep through directories. Grep allows you to recurse, but I am in the habit of using it within find to do the same thing:
find . -exec grep -H "Quicktime" {} \\;
Why do this instead of using the built-in recursive features? simply because I know find well and when I want it's powerful filtering features to work with, this makes them readily available. For example, if knew I wanted to search for "Quicktime" in files that were created in my Documents folder within the last week:
find ~/Documents -ctime 7 -exec grep -H "Quicktime" {} \\;
So, why not use Spotlight? I do. But sometimes I want a scaple rather than a chainsaw and grep combined with find give me that.