How to fix “No newline at end of file” warning for lots of files?

前端 未结 11 1840
抹茶落季
抹茶落季 2020-12-03 01:48

I have a huge number of source files that are all lacking a newline at the end.

How do I automatically add a newline to the end of each of them?

Some may alr

11条回答
  •  醉酒成梦
    2020-12-03 02:21

    find -type f | while read f; do [[ `tail -c1 "$f"` ]] && echo >> "$f"; done

    I'm using find instead of for f in * as it is recursive and the question was about "huge number of source files".

    I'm using while read instead of find -exec or xargs for performance reasons, it saves spawning shell process every time.

    I'm taking advantage of the fact that backtick operator is returning output of command "with any trailing newlines deleted" man bash, so for properly terminated files backtick will be empty and echo will be skipped.

    The find | read couple will fail on filenames that contain newlines, but it's easy to fix if required:

    find -type f -print0 | while read -d $'\0' f; do [[ `tail -c1 "$f"` ]] && echo >> "$f"; done

提交回复
热议问题