[TIP] Count non-empty lines in a text file

grep -c -v '^$' filename

If you want to, as well, exclude lines which contain only spaces:
grep -c -v '^ *$' filename

Notes (from the grep man page):
-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.)

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

Anchoring
The caret ^ and the dollar sign $ are meta-characters that respectively match the empty string at the beginning and end of a line.

Advertisement

Post a Comment

Required fields are marked *
*
*

Follow

Get every new post delivered to your Inbox.