Count number of blank lines in a file

前端 未结 7 1045
抹茶落季
抹茶落季 2021-02-01 01:38

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

7条回答
  •  没有蜡笔的小新
    2021-02-01 02:17

    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
    

提交回复
热议问题