Quote:
Originally Posted by mkyp
I'm having a problem with -exec on the find command.
I would like to get a count of a particular string in each file.
I tried: logs> find . -name "*access*2009.09*" -exec grep aString {} | wc \;
find: missing argument to `-exec'
wc: ;: No such file or directory
How do I pipe the output of grep into another command using the find -exec?
NOTE: I tried the following, but that gives the wc for all of the files, not for EACH file. logs> find . -name "*access*2009.09*" -exec grep aString {} \; |wc
1257 30271 830725
|
Code:
How do I pipe the output of grep into another command using the find -exec?
Why are you assuming "-exec" is the solution to your problem? It isn't. Do it this way:
Code:
search="search-spec"
path="/path/of/interest"
find $path | grep -iP "\.html?$" | while read filepath
do
count=$(grep -c "$search" < $filepath)
if [ $count -gt 0 ]
then
echo "$count occurrence(s) of \"$search\" found in \"$filepath\""
fi
done
Rule 1:
Do not ever use the "-exec" option from "find". It is an express path to the dark side. This forum contains any number of endless threads from people trying to make "-exec" work for them, and all that is resolved is that some people sound extremely clever in creating incomprehensible, untrustworthy one-liners, while others (e.g. newbies) end up with their problems still unresolved (people just like you).
Rule 2: If you do not understand how it works,
do not use it. Computer science is not about applying magic solutions to ordinary problems, it is about applying ordinary solutions to ordinary problems.
The above script is very easy to understand, and is certainly more robust and reliable than anything that uses -exec. It works this way:
1. Recursively search for files along a specified path.
2. Filter by a specified filename suffix (you may want to edit this to suit your own needs).
3. Read the resulting file paths -- this method correctly handles paths with embedded spaces.
4. Read the file itself and get a total of the number of occurrences of the search string in each file.
5. Test the result and only print file paths that yielded successful searches.
Many people in forums like this cannot resist saying, "But I can write that in
one line, and everyone will think I'm a genius!" To which I reply:
1. Any program can be written in one line.
2. The fact that (1) is true is not by itself a justification for actually doing it.
3. One-line programs, originally incomprehensible only to their victims, eventually become incomprehensible to their authors.
Notwithstanding the valiant efforts of many candidates, computer programming isn't a priesthood. Knowing how to code should eventually become more like knowing how to write.