Shell script to remove trailing white space from all lines in a file.

#!/usr/bin/env bash
#
# Removes trailing white space from lines.
#
# Usage: remove_traling_ws <SOURCE_FILE> [OUTPUT_FILE]
#

progname=$(basename $0)
procid=$$
temp="/tmp/${PROGNAME}_${procid}.$RANDOM"

trailingws_=$'s/[ \t]*$//'

function usage()
{
    echo -e "   Usage: $PROGNAME <SOURCE_FILE> [OUTPUT_FILE]"
    echo ""
    exit $1
}

function cleanup
{
    rm -rf "$temp" 2>/dev/null
}

[ -z "$1" ] && usage 1

if [ ! -f "$1" ]; then
    echo ""
    echo "* File not found: $1"
    echo ""
    exit 1
fi

wsfile="$1"
outfile=
if [ ! -z "$2" ]; then
    outfile="$2"
fi

# Remove trailing whitespace from file
echo "=> Remove trailing whitespace: `basename $wsfile`" >&2
cat "$wsfile" | sed "$trailingws_" >"$temp"

if [ ! -z "$outfile" ]; then
    cat "$temp" >"$outfile"
else
    cat "$outfile"
fi

cleanup