git grep --name-only --null -I '' | xargs -0 sed -i '' -e '$a\'

Adds a final newline, if one is not already there, to all non-binary files in your Git repository.


git grep:

  • --name-only: Show only the filenames.
  • --null: Terminate filenames with the null character to properly handle spaces in them.
  • -I: Don’t match binary files.
  • '': Match any non-empty file.

xargs:

  • -0: Handle filenames terminated with the null character (as given by git grep --null).

sed:

  • -i '': Edit files in-place without saving backups. With GNU sed, -i is sufficient.
  • -e '$a\': Executes a sed command. $a\ is best explained by this comment.

Afterwards, feel free to add insert_final_newline = true to your .editorconfig.

Thank you to this Stack Overflow answer and this Unix & Linux Stack Exchange answer.