Learning the Mac OS X Terminal, Part 3
Subject:   locate
Date:   2002-02-27 06:17:41
From:   pmccann
OK, someone is going to mention that locate, while nice, is not **nice enough**, so I might as well get the ball rolling. It's quoting regimen is pretty awful and it can't do a lot of things that you'd like it to do: case insensitive matches come to mind here.

Given that this is a series about the CLI I'll skip carefully over the fact that there's a really nice GUI application called "Locator" (see, which covers up these inadequacies. [[Unsubtle hint: get it!]] Instead, here's how to mimic what "Locator" does from the command line. The key is to feed the output from the command

locate \*

into another application that's more capable than locate at filtering the output. The command above just outputs *everything* in the database. So let's say you wanted to find a file that you remember downloading, called something like "applescriptlanguageguide". You feed that to locate and it says "nothing doing". So instead feed the "locate \*" command output to grep, and ask it to match for "applescriptlanguage" case insensitively.

locate \* | grep -i "applescriptlanguage"

Bingo: it takes a couple of seconds, but the file --with its mixed capitalization-- is found. The "pipe" symbol "|" just means: make the output from the command on the left of the pipe the input for the command on the right.

So that's not unhelpful, but it relied on you having a pretty decent recollection of the file name! Suppose you knew it was something like "applescript" followed by something like "language", with maybe something in between. We're drifting towards regular expressions (very gently!) here, and that's maybe what I'm suggesting for future columns: grepping for profit and pleasure, maybe in concert with "sort" and "cut" or their kinfolk.

In any case, here's what you'd do if that's all the information you could remember about the filename.

locate \* | grep -i "applescript.*language"

The .* in the pattern that you're asking grep to find just means "any character (that's the dot), occurring zero or more times (that's the star)". And you'll probably find a longish list of matches, especially if you've installed the Developer Tools. Obviously this is becoming overly long, so I'll stop here (except to mention that "Locator" actually uses perl to do the pattern matching: those who know a little about regular expressions might want to try stuffing some of that knowledge between the two forward slashes in the following command:

locate \* | perl -ne 'print if /applescript.*language/i'

which is the perl equivalent of the above "grep" line.)

Cheers, and thanks for the helpful article,