Hi,

I wrote a ruby code that writes to a file:

open('file.txt', 'w') {|file| file.write(arr.join("\n")) }

when I try to get the number of line counts

wc -l file.txt

I get the count as 49 instead of 50. How to overcome this? My file might not have a new line at the end. That shouldn't have prevented wc to count the number of actual lines.

Dani AI

Generated

— this is expected. and are on the right track: many Unix tools treat a "line" as a byte sequence terminated by a newline character. If the file's final line has no terminating newline, the traditional line-count tool will report one fewer than the number of logical lines.

Fix the writer so the file ends with a newline. In Ruby the simplest changes are to write each element with a method that adds a newline, or append one final newline after joining. Examples:

File.open('file.txt', 'w') { |f| f.puts arr }
File.write('file.txt', arr.join("\n") + "\n")

If changing the producer is not possible, use a tool that counts records even when the last line lacks a trailing newline. AWK's record counter will return the logical line count:

awk 'END{print NR}' file.txt

To debug whether a file ends with a newline, inspect the last byte (hex) — absence of 0x0A means no trailing newline. For example:

tail -c1 file.txt | od -An -t x1

Recommendation: prefer fixing the writer so files conform to the usual Unix text-file convention (each line terminated by a newline). That avoids subtle differences across tools and platforms.

Recommended Answers

All 2 Replies

wc - word count with the -l option count the number of newlines

This is right from man wc

-l'
`--lines'
Print only the newline counts.

Most utilities work with text files. A text file, by definition, has a newline at the end. If there's no final newline, the last line will not be counted.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.