linuxbashsednewline

Add a newline only if it doesn't exist


I want to add a newline at the end of a file only if it doesn't exist. This is to prevent multiple newlines at the end of the file.

I'm hoping to use sed. Here are the issues I'm having with my current code:

sed -i -e '/^$/d;$G' /inputfile

echo file1
name1
name2

echo file2
name3
name4
(newline)

when I run my code on to the files;

echo file1
name1
name2
(newline)

echo file2
name3
name4

it adds a newline if it doesn't have one but removes it if it exists... this puzzles me.


Solution

  • Since it removes newline if it's not there, you could simply use:

    echo "" >> file;  sed -ie '/^$/d;$G' file; sed -ie '/^$/d;$G' file
    

    Adds a newline and removes everything then adds newline. Not the elegant way, but certainly works :)