21

I got wrong result from the wc -l command. After a long :( checking a found the core of the problem, here is the simulation:

$ echo "line with end" > file
$ echo -n "line without end" >>file
$ wc -l file
       1 file

here are two lines, but missing the last "\n". Any easy solution?

novacik
  • 1,497
  • 1
  • 9
  • 19
  • any reason for using `echo -n` and why you can not add `\n` at the end of `echo -n`? – Bill May 14 '13 at 01:33
  • 2
    The above is an **SIMULATION** of the problem. I don't make the files, only working with them. I got them without the last enter. – novacik May 14 '13 at 01:37
  • 3
    Don't use a screwdriver to drive in nails when there's a hammer in your toolkit :-) You may _think_ that's two lines but the doco for `wc` disagrees. – paxdiablo May 14 '13 at 01:39

2 Answers2

32

For the wc line is what ends with the "\n" char. One of solutions is grep-ing the lines. The grep not looking for the ending NL.

e.g.

$ grep -c . file        #count the occurrence of any character
2

the above will not count empty lines. If you want them, use the

$ grep -c '^' file      #count the beginnings of the lines
2
clt60
  • 62,119
  • 17
  • 107
  • 194
17

from man page of wc

 -l, --lines
              print the newline counts

form man page of echo

 -n     do not output the trailing newline

so you have 1 newline in your file and thus wc -l shows 1.

You can use the following awk command to count lines

 awk 'END{print NR}' file
Bill
  • 5,263
  • 6
  • 35
  • 50