2020-08-17 A simple bash one-liner to check a bunch of files for the terminating newline

Some time ago I had a bunch of csv files in a directory, and some of them had terminating newlines. I wanted to check if every one of them was newline-terminated. After a while of thinking, I came up with this Bash one-liner:

for f in *.csv; do tail -c1 $f; done | sort -u | diff -q - <(echo)

Simply enough, we iterate over every file, take its last character (tail puts it on a line on its own), sort these characters and eliminate duplicates. If the result is just a newline, diff​ing with a temporary file containing only a newline will report no differences, otherwise, diff will tell you that “files differ” (which means that at least one of the files did not have a terminating newline). The downside is that it doesn’t tell you which one – fixing that issue is left as an exercise to the reader. ;-)

CategoryEnglish, CategoryBlog