Counting lines without text in a file

wc

I am using Ubuntu 13.10 for a while now, programming in C++ and Python. I have some question that I can solve by making a program, but maybe there are easier ways, so here is the first question.

I can use grep to find lines with a word/pattern and then use wc to count them:

grep word somefile | wc -l

How do I count the lines that have no "text"? Those that are empty or have only spaces or tabs.

Best Answer

Your system should have GNU grep, that has an option -P to use Perl expressions and you can use that, combined with -c (so no need for wc -l):

grep -Pvc '\S' somefile

The '\S' hands the pattern \S to grep and matches all line containing anything that is not space, -v selects all the other lines (those only with space), and -c counts them.

From the man page for grep:

-P, --perl-regexp
       Interpret  PATTERN  as  a  Perl  regular  expression  (PCRE, see
       below).  This is highly experimental and grep  -P  may  warn  of
       unimplemented features.

-v, --invert-match
       Invert the sense of matching, to select non-matching lines.  (-v
       is specified by POSIX.)

-c, --count
       Suppress normal output; instead print a count of matching  lines
       for  each  input  file.  With the -v, --invert-match option (see
       below), count non-matching lines.  (-c is specified by POSIX.)
Related Question