Use Ack as a Better Grep

search

As someone who has been using grep and its variants like egrep for years, I admit they have been insanely useful. But every once in a while something comes along that improves an idea so much, you can't ignore it. Such a thing is Ack, the grep replacement.

I do a lot of software development in large codebases, and the ability to find snippets of text is paramount. Tags can be used and integrated with Emacs (or Vim, we're not all perfect), which is great for function names, but not useful for general text searches. Using grep in a code repository is a pain, and usually means some sort of hack to ignore VC directories like .svn and .git. Enter ack - similar to grep but with some more thought behind it. It ignores VC meta-data directories by default and is written in pure Perl - so it's portable and supports the full Perl regexp syntax. Having a pure-Perl version available with no dependencies also means its easy to install in shared hosting environments, where you don't have root access.

Install ack by just downloading the standalone version and put it in your command path, use CPAN (cpan App::Ack), or install a pre-packaged binary (On Debian/Ubuntu systems, the package name is ack-grep). Ack output is very readable, with highlighted matches by default as well as line numbers and file names. Here is an example:

dmaxwell@kaylee:~/tmp$ ack-grep -ai 'limit_as.+?\&rlimit' emacs-22.3 emacs-22.3/src/vm-limit.c 76: getrlimit (RLIMIT_AS, &rlimit);

Here is a screenshot so you can see the highlighting and colorization:

Ack usage and output

The -ai means 'search all, case insensitively', and tells Ack to search all filetypes, even those it knows nothing about (but still not including common VCS directories or files), while ignoring case [Note: As the ack developer Andy Lester points out in the comments, -a is not needed if you're routinely searching filetypes ack knows about, which is almost always]. Ack searches are recursive by default, so there is no need for a -r switch. You can see we used Perl's non-greedy match quantifier in the search regexp, something egrep can't do. This speeds the search up considerably.

There is much more to ack, read the docs and give it a try. I hope you'll find it as useful as I have.