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

前端 未结 11 1839
抹茶落季
抹茶落季 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:38

    OK, after complaining in the comments, there is my better solution. First, you want to know, which files are missing newlines:

    find -type f -exec sh -c "tail -1 {} | xxd -p | tail -1 | grep -v 0a$" ';' -print
    

    Not super fast (calling a couple of processes for each file), but it's OK for practical use.

    Now, when you have it, you may as well add the newline, with another -exec:

    find -type f -exec sh -c "tail -1 {} | xxd -p | tail -1 | grep -v 0a$" ';' -exec sh -c "echo >> {}" ';'
    

    Possible gotchas:

    • if filenames are bad, e.g. they have spaces, you may need tail -1 \"{}\". Or does find do it right?

    • you may want to add more filtering to find, like -name \*py, or the like.

    • think about possible DOS/Unix newlines mess before use (fix that first).

    EDIT:

    If you don't like the output from these commands (echoing some hex), add -q to grep:

    find -type f -exec sh -c "tail -1 {} | xxd -p | tail -1 | grep -q -v 0a$" ';' -print
    find -type f -exec sh -c "tail -1 {} | xxd -p | tail -1 | grep -q -v 0a$" ';' -exec sh -c "echo >> {}" ';'
    

提交回复
热议问题