Tuesday, September 16, 2008

Searching through Directories in Unix

Here is a script called "search" that will allow you to search through a hiearchy of directories for files that contain a word or phrase:

echo "The pattern is found in these files:"
find . -exec grep -il "$*" {} \;

You could type in, for example, "search green" or "search will be going". In the first case, it will return the names of files that contain "green". In the second case, it will return the names of files that contain the phrase "will be going".

Search works because of the find command. The unix find command searches directories recursively, and it has the -exec option, which allows you to specify a command to be run on any file that is found.

The format of the -exec option is: -exec command options {} \;

command and options are just the command name and any options. The {} are place holders for the file name. Find will replace them with the name of each file that it finds. The \; is used to signify the end of the command.

In this case, we are giving a grep command as the argument to the exec option.

Note that search is case insensitive so "search green" would return files with "green", "Green", "GREEN", etc.

For case sensitive searches, I have a script called searchcase. The only difference in searchcase is that the "i" in the grep is removed.

No comments: