Reputation: 2015
My apologies for such a rudimentary question, but I am attempting to count the number of blank lines in a text file with awk. This is NOT a homework assignment. Windows 10. Gawk 4.1.3
BEGIN { x=0 }
/^$/ { x=x+1 }
END { print "I found " x " blank lines." }
The output is always: I found 0 blank lines.
Thanks.
Upvotes: 2
Views: 1700
Reputation: 157967
The command should work but you can skip the initialization of x
. awk
will do it for you automatically. You can use the NF
variable for that check, if it is 0
which evaluates to false
the line is empty. Furthermore I suggest to use printf
:
!NF {x++}
END {printf "I found %d blank lines\n", x}
Btw, you can simply use grep
grep -ch '^$' file
-c
outputs only the count of occurrences found, -h
suppresses the output of the file name.
Use command substitution to interpolate the output into an echo
statement:
echo "I found $(grep -ch '^$' file) blank lines"
Upvotes: 5
Reputation: 322
Apart from the nice awk solution you've already got, the sed solution would be
sed -n '/^$/p' file |wc -l
Here -n
suppresses the normal output, p
prints the lines the line is blank - (^$
). wc -l
counts the total number of lines thus printed.
Upvotes: 1