The POSIX wc
command counts how many POSIX lines in a file. The POSIX standard defines a line as a text string with the suffix \n
. Without \n
, a pure text string can't be called a line.
But to me, it's more natural to count how many lines of text string in a file. Is there an easy way to do that?
root:[~]# printf "aa\nbb" | wc -l
1
root:[~]# printf "aa\nbb\n" | wc -l
2
root:[~]#
Best Answer
With GNU
sed
, you can use:As GNU
sed
does consider those extra characters after the last newline as an extra line. GNUsed
like most GNU utilities also supports NUL characters in its input and doesn't have a limitation on the length of lines (the two other criteria that make an input non-text as per POSIX).POSIXLy, building-up on @Inian's answer to support too-long lines and NUL bytes:
That
tr
command translates all sequences of one or more character (each byte interpreted as a character in the C locale to avoid decoding issues) other than newline to onex
character, soawk
input records will be either 0 or 1 byte long and its input contain onlyx
and newline characters.