How do I find files that do not end with a newline/linefeed?

后端 未结 12 1351
广开言路
广开言路 2021-02-01 03:45

How can I list normal text (.txt) filenames, that don\'t end with a newline?

e.g.: list (output) this filename:

$ cat a.txt
asdfasdlsad4rand         


        
12条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-01 04:23

    The best oneliner I could come up with is this:

    git grep --cached -Il '' | xargs -L1 bash -c 'if test "$(tail -c 1 "$0")"; then echo "No new line at end of $0"; exit 1; fi'
    

    This uses git grep, because in my use-case I want to ensure files commited to a git branch have ending newlines.

    If this is required outside of a git repo, you can of course just use grep instead.

    grep -RIl '' . | xargs -L1 bash -c 'if test "$(tail -c 1 "$0")"; then echo "No new line at end of $0"; exit 1; fi'
    

    Why I use grep? Because you can easily filter out binary files with -I.

    Then the usual xargs/tail thingy found in other answers, with the addition to exit with 1 if a file has no newline. So this can be used in a pre-commit githook or CI.

提交回复
热议问题