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 :/