Reputation: 125
I want to count files in directory that in its name and content contains a given word.
find ./test -maxdepth 1 -type f -iname "*main*" | wc -l
Given snippet counts files that contains "main" in name. How to change it to check if it contains "main" in its content as well?
Upvotes: 0
Views: 95
Reputation: 11593
find ./test -maxdepth 1 -type f -iname "*main*" -exec grep -q main {} \; -exec printf '\n' \; | wc -l
-exec printf '\n' \;
instead of -print
protects against filenames with newline characters.
Upvotes: 0
Reputation: 6602
Loop over your files and use grep -q
which suppresses grep output:
for file in `find ./test -maxdepth 1 -type f -iname "*main*"`; do
if grep -q main $file; then
wc -l $file
fi
done
Output
5 ./test/foo_main
Upvotes: 1