Number of files not containing given string

With GNU or OpenBSD grep:

grep -L "string" ./* | grep -c /

Another POSIX way:

c=0
for f in *; do
  [ -d "$f" ] && continue
  { grep -q string || c=$(($c + 1)); } < "$f"
done
echo "$c"

By redirecting the command group instead of grep alone, we avoid counting as 1 the files which we cannot open (like files which we don't have read permission for, or * if there's no non-hidden file in the current directory).

With GNU grep, the equivalent would be:

grep -d skip -L foo ./* | grep -c /

Note that you can't use wc -l as filenames can be made of several lines. Having ./ also avoids problems with filenames that start with - or are - (which -- doesn't work around). Note that it ignores dot files.


Here's a POSIX-compliant way, in case you don't have grep -L:

for file in *; do
    awk '/string/ { found=1; exit } END{ if(!found) { printf "x" } }' < "$file"
done | wc -c

Tags:

Shell

Grep

Files