4

I have a .txt file that has 10781 lines in it. When I run wc -l on the file I get a return of 10780.

If I add a blank line at the end of the .txt I get the correct result of 10781. Can someone explain what exactly wc -l counts?

17

Probably your last line does not have a newline.

See this:

$ printf bla > file
$ wc -l file
0 file

$ man 1p wc

-l Write to the standard output the number of newlines in each input file.

On Unix it's good style to have a newline character at the end of text files. If you can't repair your files you can use these workarounds to count the last "line" always: https://stackoverflow.com/questions/28038633/wc-l-is-not-counting-last-of-the-file-if-it-does-not-have-end-of-line-character

4
  • ah, yes, that makes sense. Thank you @rudimeier – Bleakley Oct 4 '16 at 15:08
  • 1
    At the end of non-empty text files; your 0 length file is how we represent zero lines; if we add a newline, then it contains 1 line. :) I.e. it's a line terminator, not a file terminator. – Kaz Oct 4 '16 at 19:50
  • 5
    "On Unix it's good style to have a newline character at the end of text files." -- The only way a text file can not end in newline is if the file is empty. If it ends in any other character, then by definition it is not a text file, due to how POSIX describes what a text file is. – hvd Oct 4 '16 at 20:05
  • 1
    Actually I guess POSIX defined wc -l as is to make sure that cat a b | wc -l is always the same as wc -l a + wc -l b. Otherwise the output "total count" of wc -l a b would be ambiguous. – rudimeier Oct 4 '16 at 20:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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