I am trying to run the find
command to find the total number of occurrences of a particular text string and also the number of files which has this text string.
What I have right now is this command.
find . -name "*.txt" | xargs grep -i "abc"
This reports all the "*.txt" files which contain the text "abc". I want either one or two find command to get
- Total number of times abc appears
- Total number of files which has abc in it.
Best Answer
For question 1, you can do this:
find . -name "*.txt" | xargs grep -i "abc" | wc -l
This counts the total number of matches for abc in all text files.
And for question 2, I came up with:
find . -name "*.txt" -exec grep -i "abc" {} + | cut -d: -f1 | sort | uniq | wc -l
This gets just the unique filenames from the list of matches and counts them (the sort is probably not needed).
As pointed out by miracle173,
grep
comes with a "one match per file" flag so the command can be shortened to just:find . -name "*.txt" -exec grep -il "abc" {} + | wc -l