Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add missing newlines in multiple files

I have a bunch of files that are incomplete: the last line is missing an EOL character.

What's the easiest way to add the newline, using any tool (awk maybe?)?

like image 410
sidyll Avatar asked May 07 '11 17:05

sidyll


2 Answers

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
like image 124
Gilles 'SO- stop being evil' Avatar answered Nov 15 '22 13:11

Gilles 'SO- stop being evil'


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.

like image 23
Benoit Avatar answered Nov 15 '22 13:11

Benoit