I want to add a newline at the end of a file only if it doesn\'t exists, this is to prevent multiple newlines at the end of the file.
I\'m hoping to use sed. Here\'s the
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