JoeS JoeS - 1 year ago 95
Perl Question

Require exactly 1 trailing newline in a file

I have a mix of files with various ways of using trailing new lines. There are no carriage returns, it's only

. Some files have multiple newlines and some files have no trailing newline. I want to edit the files in place.

How can I edit the files to have exactly 1 trailing newline?

Answer Source

To change text files in-place to have one and only one trailing newline:

 sed -zi 's/\n*$/\n/'

This requires GNU sed.

-z tells sed to read in the file using the NUL character as a separator. Since text files have no NUL characters, this has the effect of reading the whole file in at once.

-i tells GNU sed to change the file in place.

s/\n*$/\n/ tells sed to replace however many newlines there are at the end of the file with a single newline.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download