Add missing newlines in multiple files Add missing newlines in multiple files bash bash

Add missing newlines in multiple files


To add a newline at the end of a file:

echo >>file

To add a line at the end of every file in the current directory:

for x in *; do echo >>"$x"; done

If you don't know in advance whether each file ends in a newline, test the last character first. tail -c 1 prints the last character of a file. Since command substitution truncates any final newline, $(tail -c 1 <file) is empty if the file is empty or ends in a newline, and non-empty if the file ends in a non-newline character.

for x in *; do if [ -n "$(tail -c 1 <"$x")" ]; then echo >>"$x"; fi; done


Vim is great for that because if you do not open a file in binary mode, it will automatically end the file with the detected line ending.

So:

vim file -c 'wq'

should work, regardless of whether your files have Unix, Windows or Mac end of line style.


echo >> filename

Try it before mass use :)