stringbashis-emptyline-count

How do I count the number of lines in a bash variable, respecting emptiness?


We know how to count the number of lines in a variable. However, as noted in comments and answers there, the semantics are quirky when it comes to empty variables, as an empty variable is usually counted the same as a non-empty, no-newline variable:

$ echo -n "" | wc -l
0
$ echo -n "foo" | wc -l
0
$ echo "" | wc -l
1
$ echo "foo" | wc -l
1

not so good, if you want to count the number of results some other command returned.

Now, a partial workaround is suggested in one of the answers to that question:

printf "%s" "$a" | grep -c "^"

but that's not exactly what I'm after either, since it counts a non-empty variable whose value is a newline as having 0 lines.

My question: Other than counting "regularly" and then explicitly checking for the case of emptiness, is there a decent way to obtain such a count in bash?


Solution

  • awk to the rescue:

    $ echo -n "foo" | awk 'END {print NR}'
    1
    $ echo -n "" | awk 'END {print NR}'
    0