carlosmarti
carlosmarti

Reputation: 83

Real bash line count

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?

Upvotes: 2

Views: 85

Answers (2)

karakfa
karakfa

Reputation: 67557

awk to the rescue!

awk 'END{print NR}' file

will work fine without the trailing newline.

Upvotes: 2

John Kugelman
John Kugelman

Reputation: 362037

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

Upvotes: 3

Related Questions