1

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?

4
  • "It counts a non-empty variable holding a newline as having 0 lines" – does it? This printf "%s" $'x\n' | grep -c "^" returns 1 for me. Mar 31, 2020 at 15:48
  • @BenjaminW.: I meant holding just a newline with nothing else.
    – einpoklum
    Mar 31, 2020 at 16:01
  • Do you want to count empty lines after the first one? What should be the result of printf "a\n\n\n\nb\n" | countcommand and data not ending with a newline: printf "a\nb" or printf "a\n" ?
    – Walter A
    Apr 1, 2020 at 8:31
  • 1
    @WalterA: Pretend that it's some shell utility the produces that output. Those typically finish things off with a newline for the prompt to be on line start. So, a\n\n\n\nb\n should give 5, I think; the last empty line, without the \n, will not be counted. a\nb - two lines but it's input I'm less likely to get. a\n - one line. Also, see edit.
    – einpoklum
    Apr 1, 2020 at 8:54

2 Answers 2

2

awk to the rescue:

$ echo -n "foo" | awk 'END {print NR}'
1
$ echo -n "" | awk 'END {print NR}'
0
1
  • 1
    Looks like the most robust solution, even if awk is a bit of a large hammer.
    – einpoklum
    Apr 1, 2020 at 8:58
0

The following will count the number of newlines:

printf %s "$var" | tr -d -c '\n' | wc -c

It will work in all instances except when the last line is missing a newline.


You can test separately if a variable is empty like this:

test -z "$var" && echo "var is empty"

test -n "$var" && echo "var is not empty"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.