Shell

How to count blank lines and non-blank lines in a file

bash Here are shell techniques for counting blank and nonblank lines, which you can build on for other tasks or troubleshooting.

Count blank lines in a file

[tum@ezylinux ~]$ grep "^$" /path/to/textfile | wc -l

or

[tum@ezylinux ~]$ grep -cvP '\S' /path/to/textfile

Count nonblank lines in a file

[tum@ezylinux ~]$ cat /path/to/textfile |sed '/^\s*$/d' | wc -l

or

[tum@ezylinux ~]$ grep -cP '\S' /path/to/textfile

To count nonblank lines while also excluding comments (#):

[tum@ezylinux ~]$ cat /path/to/textfile |sed '/^\s*#/d;/^\s*$/d' | wc -l
EOF.← Back to articles