Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of blank lines in a file

In count (non-blank) lines-of-code in bash they explain how to count the number of non-empty lines.

But is there a way to count the number of blank lines in a file? By blank line I also mean lines that have spaces in them.

like image 254
Sudar Avatar asked Nov 22 '12 04:11

Sudar


People also ask

How do I count the number of blank lines in a file?

'grep -cv -P '\S' filename' will count the total number of blank lines in the file.

How do you grep for blank lines?

To match empty lines, use the pattern ' ^$ '. To match blank lines, use the pattern ' ^[[:blank:]]*$ '. To match no lines at all, use the command ' grep -f /dev/null '.

How do you count the number of blank lines in a file in Python?

Therefore, sum(line. isspace() for line in f) returns the number of lines that are considered empty.

Which command is used to count lines from file?

Use the wc command to count the number of lines, words, and bytes in the files specified by the File parameter.


2 Answers

Another way is:

grep -cvP '\S' file 
  • -P '\S'(perl regex) will match any line contains non-space
  • -v select non-matching lines
  • -c print a count of matching lines

If your grep doesn't support -P option, please use -E '[^[:space:]]'

like image 149
kev Avatar answered Sep 28 '22 02:09

kev


One way using grep:

grep -c "^$" file 

Or with whitespace:

grep -c "^\s*$" file  
like image 36
Steve Avatar answered Sep 28 '22 02:09

Steve