Linux – sed: Add new line to every file that does not have one at end of file

linuxsed

I am getting countless

warning: no newline at end of file

From some code that was last edited in Windows.

In Linux, how can I fix all these cpp/h files and add a new line to the end of every file that does not have a new line?

I've been trying to use sed:

find . \( -name "*.cpp" -o -name "*.h" -o -name "*.hpp" \) -print | xargs sed -i -e "$G"

But I haven't gotten it working yet.

Best Answer

In the absence of dos2unix - which would be the ideal way, try:

find . \( -name "*.cpp" -o -name "*.h" -o -name "*.hpp" \) -print0 | xargs -0 -iFILE sh -c 'echo >> FILE'

or

find . -type f \( -name "*.cpp" -o -name "*.h" -o -name "*.hpp" \) -exec sh -c 'echo >> {}' \;

Note that redirection is always a problem - the replacement doesn't occur as desired without launching a new shell.

Since your question was about 'sed', you could also do it as:

find . \( -name "*.cpp" -o -name "*.h" -o -name "*.hpp" \) -print0 | xargs -0 sed -i -e '$a\
\'

(That is a literal new line character - not a \n or anything else - probably best done as copy and paste - as it might be rather hard to type in :).