Count number of blank lines in a file

别来无恙 提交于 2019-12-02 18:47:50

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:]]'

One way using grep:

grep -c "^$" file

Or with whitespace:

grep -c "^\s*$" file 

You can also use awk for this:

awk '!NF {sum += 1} END {print sum}' file

From the manual, "The variable NF is set to the total number of fields in the input record". Since the default field separator is the space, any line consisting in either nothing or some spaces will have NF=0.

Then, it is a matter of counting how many times this happens.

Test

$ cat a
aa dd

ddd


he      llo
$ cat -vet a # -vet to show tabs and spaces
aa dd$
    $
ddd$
   $
^I$
he^Illo$

Now let's' count the number of blank lines:

$ awk '!NF {s+=1} END {print s}' a
3

grep -cx '\s*' file

or

grep -cx '[[:space:]]*' file

That is faster than the code in Steve's answer.

Majid Azimi

Using Perl one-liner:

perl -lne '$count++ if /^\s*$/; END { print int $count }' input.file
grep -v '\S' | wc -l

(On OSX the Perl expressions are not available, -P option)

Luca Davanzo

To count how many useless blank lines your colleague has inserted in a project you can launch a one-line command like this:

blankLinesTotal=0; for file in $( find . -name "*.cpp" ); do blankLines=$(grep -cvE '\S' ${file}); blankLinesTotal=$[${blankLines} + ${blankLinesTotal}]; echo $file" has" ${blankLines} " empty lines."  ; done; echo "Total: "${blankLinesTotal}

This prints:

<filename0>.cpp #blankLines
....
....
<filenameN>.cpp #blankLines
Total #blankLinesTotal
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!