Using version control systems I get annoyed at the noise when the diff says No newline at end of file .

Tell me the best way to add a new line at the end of a file and get rid of those messages?

Best Answer


Here you go .

sed -i -e '$a\' file

And alternatively for OS X sed .

sed -i '' -e '$a\' file

This adds \n at the end of the file only if it doesn’t already end with a newline. So if you run it twice, it will not add another newline.

$ cd "$(mktemp -d)"
$ printf foo > test.txt
$ sed -e '$a\' test.txt > test-with-eol.txt
$ diff test*
1c1
< foo
\ No newline at end of file
---
> foo
$ echo $?
1
$ sed -e '$a\' test-with-eol.txt > test-still-with-one-eol.txt
$ diff test-with-eol.txt test-still-with-one-eol.txt
$ echo $?
0