Better Than Grep

April 20th, 2010

A co-worker recently introduced me to a sweet Unix terminal command “ack.” Ack is a grep replacement (or supplement) that allows you to search your file system, but ignores folders like .svn, cvs, and other folders you would not want to search on a version-controlled project. Ack is fast, cross-platform, and easy to use.

Test Drive Ack

Lets say you are working on a project that was passed on to you by another developer, and you are having trouble finding a template to change some simple HTML. Lets also pretend that your templates are smarty template files (.tpl) and some are PHP. Finding a unique attribute in the source of your HTML browser, you could do an ack search in your terminal to locate your template:

cd /path/to/project
ack myUniqueId -G ".tpl|.php"

The above search will return and highlight search in all files and line numbers that match “myUniqueId” in files that have “.tpl” or “.php” in them. This is not to say that only php and tpl files will be returned, but all types of files that contain “.tpl” or “.php”. Chances are good that only php and tpl files would be returned in this case, but -G is not matching file extensions exclusively.

Let’s break this command down:

  • This references ack, make sure ack was properly setup (see the ack homepage for more info on setup)
  • The second argument matches a regex pattern and serves as your search string.
  • -G “.tpl|.php” matches filenames that contain “.php” and “.tpl”.

Ack also has built-in support for various file types. If you were doing the same search above, but only cared about PHP files, you could execute the following command:

ack myUniqueId --php

The possibilities are rather endless :) . If you find this helpful and interesting, let me know, I may do a follow-up post with more in-depth examples.

Update 4/20/2010: As pointed out in the comments, I had a typo in the first example and the explanation was incorrect. Sorry about that :/

2 Responses to “Better Than Grep”

  1. Andy Lester
    Posted on Apr 20th, 2010
    at 10:36 am #

    “tpl|php” doesn’t really say “only files with the extension .tpl or .php”. It’s going to match any filename with tpl or php in it, anywhere.

    I’m wondering what that first example

    ack myUniqueId -a -g “tpl|php”

    does for you, because it doesn’t make sense to use both a regex (myUniqueId) and the -g flag together.

  2. Paul Redmond
    Posted on Apr 20th, 2010
    at 2:44 pm #

    I fixed this post. Thanks for pointing out my mistakes in the post. Sorry if I confused anyone (obviously, I was confused) :)

Leave a Comment.

About the Author

Paul Redmond I'm Paul Redmond, a web designer, programmer, and marketer living in Phoenix, Arizona. I am an expert with CSS, JavaScript, and Frontend development; I also program applications using PHP, Ruby, and Rails.

Web Stuff I Highly Recommend

Basecamp Media Temple(MT)