2

I'm parsing a temp file whose lines would like removed so I run: tr '\n' ' ' < temp > temp2. Now when I wc -l temp2 it is returning 0 lines instead of 1 which was unexpected for me.

After checking the manual, wc -l counts just the newlines and not the lines. Its behaviour is fine but might be problematic if you don't know if the last line of a file contains a line feed.

Is there any tool or workaround that count lines even if they have no linefeed?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

2 Answers2

3

UNIX text files must always have a trailing newline. Without it, many tools will fail to process the last line, exactly as you are seeing. Rather than looking for a tool that can handle it I'd fix the error in your file.

{ tr '\n' ' ' < temp && echo; } > temp2
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Thank you very much John but then this makes me wonder: Shouldn't the redirection have created the trailing newline, in order to make a valid file ? – carlosmarti May 30 '18 at 18:55
  • @carlosmarti: redirection is not limited to text files. `wc`, on the other hand, is. – rici May 30 '18 at 19:49
2

awk to the rescue!

awk 'END{print NR}' file

will work fine without the trailing newline.

karakfa
  • 66,216
  • 7
  • 41
  • 56
  • While my situation is explained by John Kugelman's answer, this addresses the original broad question since the file might not be a text file – carlosmarti May 30 '18 at 20:13