Add a newline only if it doesn't exist Add a newline only if it doesn't exist bash bash

Add a newline only if it doesn't exist


sed

GNU:

sed -i '$a\' *.txt

OS X:

sed -i '' '$a\' *.txt

$ addresses the last line. a\ is the append function.

OS X's sed

sed -i '' -n p *.txt

-n disables printing and p prints the pattern space. p adds a missing newline in OS X's sed but not in GNU sed, so this doesn't work with GNU sed.

awk

awk 1

1 can be replaced with anything that evaluates to true. Modifying a file in place:

{ rm file;awk 1 >file; }<file

bash

[[ $(tail -c1 file) && -f file ]]&&echo ''>>file

Trailing newlines are removed from the result of the command substitution, so $(tail -c1 file) is empty only if file ends with a linefeed or is empty. -f file is false if file is empty. [[ $x ]] is equivalent to [[ -n $x ]] in bash.


Rather than processing the whole file with see just to add a newline at the end, just check the last character and if it's not a newline, append one. Testing for newline is slightly interesting, since the shell will generally trim them from the end of strings, so I append "x" to protect it:

if [ "$(tail -c1 "$inputfile"; echo x)" != $'\nx' ]; then    echo "" >>"$inputfile"fi

Note that this will append newline to empty files, which might not be what you want. If you want to leave empty files alone, add another test:

if [ -s "$inputfile" ] && [ "$(tail -c1 "$inputfile"; echo x)" != $'\nx' ]; then    echo "" >>"$inputfile"fi


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 :)