2

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.

CaitlinG
  • 1,955
  • 3
  • 25
  • 35
  • 2
    Your solution works for me. Do you also consider whitespace-only lines blank? – eush77 Jul 16 '16 at 07:09
  • 2
    gawk 'NF==0{x++} END{ print "I found " x " blank lines." }' file – Chet Jul 16 '16 at 07:14
  • 1
    Since it works according to eush77, it might just be a line-terminator issue. Maybe try piping through `dos2unix` first. – matz Jul 16 '16 at 07:21
  • 1
    `grep -cvP '\S' file` or `awk /^[[:space:]]*$/ {x++}` should work. – dawg Jul 16 '16 at 14:38
  • 1
    Do you have that script saved in a file which you're executing with `awk -f script input` or are you trying to evoke it from the command line with `awk 'BEGIN{...}' input`? If the former, good, if that latter, do the former instead. @Chet if you remove the OPs BEGIN section, which you should, then you need to use printf `%d` or use `x+0` to avoid getting a null instead of zero output for empty files. – Ed Morton Jul 16 '16 at 19:45

2 Answers2

5

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"
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
1

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.

Мона_Сах
  • 322
  • 3
  • 12