LoginSignup
14
12

More than 5 years have passed since last update.

余計な差分“No newline at end of file”を何とかしたい

Last updated at Posted at 2013-12-11

とあるファイルをVimで修正して保存したら、元のファイルに改行コード(\n)がなくて
Git等で余計な差分が出て困る場合の対処方法

事前にファイル末尾に\nがないやつを探し出して、一括修正する。
例えばカレント配下の*.jspなら

find . -type f -name '*.jsp' -exec sh -c "tail -1 {} | xxd -p | tail -1 | grep -q -v 0a$" ';' -exec sh -c "echo >> {}" ';'
やっていること
  • find -execで見つかったファイルに対して処理。ここではsh -cでダブルクォート内部をシェル実行。’;’-execの終端子。
  • tail -1で最終行のみ出力
  • xxd -pで素のhex dump
  • grep -q -v 0a$でサイレントモードで末尾に0a(=\n)が無い物を探す。
  • 見つかった末尾改行がないファイルに対してecho >>して改行を追記。-execは連鎖の絞り込みが効く模様。

もっとエレガントな方法はないものか・・・

参考

objective c - How to fix “No newline at end of file” compiler warning for lots of files - Stack Overflow

14
12
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
12