8

I wonder how does wc work? Most times it seems to return the number of lines, but sometimes it seems to be newlines? In the man page its newlines. But:

[jiewmeng@JM textFiles]$ echo -e "\n\n" | wc -
      3       0       3 -

If the above returns the number of newlines, it should just return 2? Also I got this wierd file:

[jiewmeng@JM textFiles]$ cat testA.txt 
The quick
brown fox
jumped over
the lazy 
dog.[jiewmeng@JM textFiles]$ wc testA.txt 
 4  9 50 testA.txt

In the above case, it appears to be returning the number of newlines?

3 Answers 3

15

In your first example echo will add it's newline at the end, you can stop this by adding the -n option to echo.

wc counts characters, words and lines, lines are defined as zero or more characters ending in line feed (\n).

1
  • "lines are defined as zero or more characters ending in line feed \n", to put differently, the number of \ns (in case somebody is confused with this respect) Jun 17, 2020 at 9:04
12

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 '^'.

9

Your assumption is correct. wc -l counts the number of newlines (\n). As XTian said, echo adds a newline to the end of everything it prints unless you tell it not to with -n with some implementations or by including \c in some others (Unix conformant ones).

You can check that this is what's going on by piping through od -c:

$ echo -e '\n\n' | od -c
0000000  \n  \n  \n
0000003

So wc -l correctly counts three lines.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .