home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    

UNIX Power Tools

UNIX Power ToolsSearch this book
Previous: 17.20 grepping a Directory Tree (and a Gotcha) Chapter 17
Finding Files with find
Next: 17.22 Finding the Links to a File

17.21 lookfor: Which File Has that Word?

The following simple shell script, lookfor , uses find ( 17.1 ) to look for all files in the specified directory hierarchy that have been modified within a certain time, and it passes the resulting names to grep ( 27.2 ) to scan for a particular pattern. For example, the command:


lookfor /work -7 tamale enchilada

would search through the entire /work filesystem and print the names of all files modified within the past week that contain the words "tamale" or "enchilada". (So, for example: if this article is stored on /work , lookfor should find it.)

The arguments to the script are the pathname of a directory hierarchy to search in ( $1 ), a time ( $2 ), and one or more text patterns (the other arguments). This simple but slow version will search for an (almost) unlimited number of words:

trap 'rm -f $temp; exit' 0 1 2 15
find $1 -mtime $2 -print > $temp
shift; shift
for word
do grep -i "$word" `cat $temp` /dev/null

That version runs grep once to search for each word. The -i option makes the search find either uppercase or lowercase letters. Using /dev/null makes sure that grep will print the filename . ( 13.14 ) Watch out: the list of filenames may get too long ( 9.20 ) .

The next version is more limited but faster. It builds a regular expression for egrep ( 27.5 ) that finds all the words in one pass through the files. If you use too many words, egrep will say Regular expression too long . Your egrep may not have a -i option; you can just omit it. This version also uses xargs ( 9.21 ) ; though xargs has its problems ( 9.22 ) .

shift; shift
# Build egrep expression like (word1|word2|...) in $expr
for word
    case "$expr" in
    "") expr="($word" ;;
    *) expr="$expr|$word" ;;

find $where -mtime $when -print | xargs egrep -i "$expr" /dev/null

- JP , TOR

Previous: 17.20 grepping a Directory Tree (and a Gotcha) UNIX Power Tools Next: 17.22 Finding the Links to a File
17.20 grepping a Directory Tree (and a Gotcha) Book Index 17.22 Finding the Links to a File

The UNIX CD Bookshelf Navigation The UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System