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

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

    pcregrep --recursive --exclude-dir=.git \
      --files-without-match --multiline '\n\z' . |
      while read k ; do echo >> "$k"; done
    

    There are several steps involved here:

    1. Recursively find files
    2. Detect which files lack a trailing new line
    3. Loop over each of those files
    4. Append the newline

    Step 1 is traditionally done with find (following the Unix tradition of "each tool doing one thing and doing it well"), but since pcregrep has builtin support, I'm comfortable using it. I'm careful to avoid messing around with the .git folder.

    Step 2 is done with a multiline regular expression matching files that do have a final newline, and printing the names of files that don't match.

    Step 3 is done with a while/read loop rather than a for/in, since the latter fails for filenames with spaces and for extremely long lists of files.

    Step 4 is a simple echo, following @norman-ramsey's approach.

    h/t @anthony-bush https://stackoverflow.com/a/20687956/577438 for the pcregrep suggestion.

提交回复
热议问题