How to remove trailing whitespaces with sed?

Viktor picture Viktor · Dec 14, 2010 · Viewed 162.1k times · Source

I have a simple shell script that removes trailing whitespace from a file. Is there any way to make this script more compact (without creating a temporary file)?

sed 's/[ \t]*$//' $1 > $1__.tmp
cat $1__.tmp > $1
rm $1__.tmp

Answer

codaddict picture codaddict · Dec 14, 2010

You can use the in place option -i of sed for Linux and Unix:

sed -i 's/[ \t]*$//' "$1"

Be aware the expression will delete trailing t's on OSX (you can use gsed to avoid this problem). It may delete them on BSD too.

If you don't have gsed, here is the correct (but hard-to-read) sed syntax on OSX:

sed -i '' -E 's/[ '$'\t'']+$//' "$1"

Three single-quoted strings ultimately become concatenated into a single argument/expression. There is no concatenation operator in bash, you just place strings one after the other with no space in between.

The $'\t' resolves as a literal tab-character in bash (using ANSI-C quoting), so the tab is correctly concatenated into the expression.