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:
% 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 (
#!/bin/sh temp=/tmp/lookfor$$ 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 done 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
#!/bin/sh where="$1" when="$2" shift; shift # Build egrep expression like (word1|word2|...) in $expr for word do case "$expr" in "") expr="($word" ;; *) expr="$expr|$word" ;; esac done expr="$expr)" find $where -mtime $when -print | xargs egrep -i "$expr" /dev/null - , |
|