My script for removing trailing white spaces from files

This post was written by eli on June 6, 2012
Posted Under: Linux,perl

Git has this thing about trailing white spaces in source files, for good reasons. Somehow it looks like there isn’t a widely spread utility for cleaning up a lot of files in one go. On the other hand, there are plenty of them out there, but none met my needs. So I wrote yet another one. Here it is.



for ((i=0; i<numargs; i=i+1)) ; do
 if [ -e "$1" ] ; then
 /usr/bin/perl -p0777e 'exit ((/[ \t]+$/m) ? 1 : 0)' "$1" || echo Trimmed \"$1\"
 /usr/bin/perl -pi.orig-$$ -e 's/[ \t]+$//' "$1" && rm -f "$1.orig-$$"
 echo "***" No such file \"$1\" "***"

Among the things it does good, is that it accepts the files to trim as arguments, so it’s comfy to use from command line. Another thing is that it tells you which files it trimmed, and which ones it didn’t find. And what it also does, is to create a backup file (by adding a .orig+process number prefix) which is deleted immediately after a successful trimming. Just in case the system crashes right in the middle of trimming a file.

There is a slight problem with the “Trimmed” message appearing before actually trimming each file. This can be somewhat confusing if the script is interrupted in the middle of action.

Neither am I so happy with having two (slightly) different regular expressions for producing the message and doing the work. Maybe there’s some corner case I wasn’t aware of, which can produce false reporting.

In retrospective, I should have done this as a Perl script, and not as a bash script doing two one-liners. But I don’t have any motivation to fix this. If it ain’t broke… (yet?)

Add a Comment

required, use real name
required, will not be published
optional, your blog address