Ubuntu – How to find out how many files ending in .c or .cpp inside a directory contain the string: string

16.04command linefiles

How can I find out how many files ending in .c or .cpp inside a directory contain the string: string?

The string can occur anywhere in the entire file, including comments or as part of a larger string.

Best Answer

If you know that your filenames cannot contain newlines, then

grep -rFl --include='*.c' --include='*.cpp' string . | wc -l

Otherwise

find . -type f \( -name '*.c' -o -name '*.cpp' \) -exec grep -Fq string {} \; -printf x | wc -c