Count number of blank lines in a file

2019-03-10 16:18发布

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.

7条回答
戒情不戒烟
2楼-- · 2019-03-10 17:00

One way using grep:

grep -c "^$" file

Or with whitespace:

grep -c "^\s*$" file 
查看更多
家丑人穷心不美
3楼-- · 2019-03-10 17:05

Using Perl one-liner:

perl -lne '$count++ if /^\s*$/; END { print int $count }' input.file
查看更多
我只想做你的唯一
4楼-- · 2019-03-10 17:06
grep -v '\S' | wc -l

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

查看更多
小情绪 Triste *
5楼-- · 2019-03-10 17:08

grep -cx '\s*' file

or

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

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

查看更多
Animai°情兽
6楼-- · 2019-03-10 17:12

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

ffffd


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

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

$ awk '!NF {s+=1} END {print s}' a
3
查看更多
叼着烟拽天下
7楼-- · 2019-03-10 17:12

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
查看更多
登录 后发表回答