Reputation: 23497
Count the occurrences of a phrase with GREP
I have a directory containing a bunch of files. So when I need to see if any of the files contains a certain phrase, I'd use
grep 'the phrase' mydir/*
Is there any way to count the total number of times that the phrase appears in these files?
I've used grep 'the phrase' mydir/* --count
But that'd give the occurrences in each individual file, not the total, which is not what I want.
Upvotes: 1
Views: 7096
Reputation: 11
It's even simpler than the previous two responses:
grep 'the phrase' mydir/* | wc -l
The output of grep across all files that match "mydir/*" is then sent to wc -l.
Upvotes: 1
Reputation: 32398
This should do it:
find mydir -print0 | xargs -0 grep 'the phrase' | wc -l
find mydir -print0
- finds all the files in mydirectory and prints them as null terminated lines)
xargs -0
- converts a stream of null terminated lines and converts them into quote seperated arguments, e.g. "mydir/file 1" "mydir/file 2" ... these can now be passed into the arument list of grep.
wc -l
- counts the number of lines
The null terminated lines business is all to do with working around files that have spaces in them since otherwise these can look like multiple arguments to grep.
Upvotes: 5
Reputation: 1015
grep 'the phrase' mydir/* --count | awk 'BEGIN { FS=":"; sum=0;} { sum = sum + $2; } END { print sum } '
Upvotes: 0