Remove Trailing Blank Lines

Recently, I wrote a utility that required the final line of text in a file to terminate with a special code. The code had to sit at the end of a line of text, not on a blank line. What I discovered is that many text files end with one or more blank lines.

The blank lines, essentially one newline character following another, are a valid part of any text file. In fact, I recall from decades ago online debates over whether text files (source code or even email messages) should end with an extra blank line “just in case.”

A text file is a text file. It need not end with a newline character at all. Yet, as I was writing my utility, I discovered that some text files didn’t end with a newline, some ended with a single newline, many with two (the last paragraph followed by a blank line), and a handful with multiple blank lines.

The task for this month’s Exercise is to write code that processes a text file, outputting all its contents minus any trailing blank lines. A final newline character is okay. No terminating newline is okay. But when the file tails with two or more newlines, they must not appear in the output.

To test the code, I’m supplying four sample files:

getty-0.txt
getty-1.txt
getty-3.txt
getty-mix.txt

Each of these files terminates with a different number of newlines: zero, one, and three for the first three. The file getty-mix.txt has multiple blank lines internally as well as at the end, just to test your code.

For your solution to work properly, the output of the first three files looks like this:

Four score and seven years ago our fathers brought
forth on this continent a new nation, conceived in
liberty, and dedicated to the proposition that all
men are created equal.

For the getty-mix.txt file, output looks like this:

Four score and seven years ago our fathers brought
forth on this continent a new nation, conceived in

liberty, and dedicated to the proposition that all

men are created equal.

No blank line follows the last line in each example.

I can think of several solutions for this Exercise. In fact, my own solution is different than the one I used for the utility I wrote that spawned this idea. Click here to view my solution. Before then, please try this Exercise on your own.

Leave a Reply