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 (the number one) 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.

Leave a Comment