steeldriver’s answersteeldriver’s answer (do cat files | grep -c <token>) was my first thought when I read your question title. But I see that, in your script snippet, you aren’t using the count, beyond comparing it to zero — i.e., you’re asking “how many are there?” when you want to know “are there any?”. Consider using -q:
if "$EGREP" -q -- 'assert\.h|cassert' *.h *.cpp then FAILED=1 echo "Found Posix assert headers" … fi Notes:
- You should always quote your shell variable references (e.g.,
"$EGREP") unless you have a good reason not to, and you’re sure you know what you’re doing. If you have definedEGREP=grep -e, that would be a reasonably good reason to say$EGREPwithout quotes, but see this answerthis answer to Security implications of forgetting to quote a variable in bash/POSIX shellsSecurity implications of forgetting to quote a variable in bash/POSIX shells. -q(or, equivalently,--quietor--silent) means “Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected.” This not only gives you the functional behavior that you want (i.e., the same functional behavior as steeldriver’s answer), but with the performance benefit thatgrepwill exit as soon as it finds a match, and doesn’t need to read all the files.- It’s advised to put
--between a command’s options and its arguments in order to prevent a filename that begins with-from being interpreted as an option string. - You don’t need to have parentheses around your entire regular expression.
grep 'assert.h'will matchassert h,assert,h,assert3h,assertph, etc. If you don’t care, that’s up to you. If you want to match onlyassert.h, grep forassert\.h.