The reason why you get 3
here has already been explained, but to add a bit more about the question in the subject:
By the strict (POSIX) definition of the term, a text line is always terminated by a newline character, so counting the number of newline characters is the same as counting the number of lines.
Sometimes though, you find files that have data after the last newline (typically, non-text files most likely do). The output of printf foo
(same as echo -n foo
or echo 'foo\c'
depending on the echo
implementation) for instance, doesn't contain any line because that foo
is not terminated by a newline character.
The behaviour of text utilities (wc
is not a text utility) is unspecified by POSIX in that case (a file that ends in a character other than newline is not a text file). There are some utility implementations that will treat those extra characters as an extra line, some which will ignore them, some may issue a warning message. Among the ones that treat it as an extra line, some will add the missing newline on output, some others won't.
What that means is that wc -l
won't necessarily give you the same result as things like sed -n '$='
or awk 'END{print NR}'
or grep -c '^'
.