Bash Shell Text Processing Newlines – How to Add a Newline to the End of a File?

bashnewlinesshelltext processing

Using version control systems I get annoyed at the noise when the diff says No newline at end of file.

So I was wondering: How to add a newline at the end of a file to get rid of those messages?

Best Answer

To recursively sanitize a project I use this oneliner:

git ls-files -z | while IFS= read -rd '' f; do tail -c1 < "$f" | read -r _ || echo >> "$f"; done

Explanation:

  • git ls-files -z lists files in the repository. It takes an optional pattern as additional parameter which might be useful in some cases if you want to restrict the operation to certain files/directories. As an alternative, you could use find -print0 ... or similar programs to list affected files - just make sure it emits NUL-delimited entries.

  • while IFS= read -rd '' f; do ... done iterates through the entries, safely handling filenames that include whitespace and/or newlines.

  • tail -c1 < "$f" reads the last char from a file.

  • read -r _ exits with a nonzero exit status if a trailing newline is missing.

  • || echo >> "$f" appends a newline to the file if the exit status of the previous command was nonzero.

Related Question