Recently I had a need to count the number of empty lines in a text file. After some digging into the
man pages of
grep I was able to come up with a one liner which was able to do it.
By empty line, I mean any line which either has no characters or has only whitespace (space, tab) characters.
For the impatient in you, here is the actual command.
-P '\S'– This selects all lines that have a non whitespace character
-c– Print the count of matching lines
-v– Select only the non-matching lines
So, we are first matching all lines that have a non whitespace character and then use
-v option to ignore them and then
-c option to print the count instead of the actual line.
If we wanted the count of all non-empty lines, then we just have to remove the
-v option from the above command.
Hope this is helpful. Happy Grep’ing