Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove trailing whitespaces with sed?

Tags:

sed

whitespace

People also ask

How do I get rid of trailing spaces in awk?

Trim Trailing Whitespaces The above command replaces one or more spaces at the end of the string ([ \t]+ $) with nothing ( “”) to remove the trailing whitespaces.

How do I remove whitespace at the end of a line in Linux?

Remove just spaces: $ sed 's/ *$//' file | cat -vet - hello$ bye$ ha^I$ # tab is still here! Remove spaces and tabs: $ sed 's/[[:blank:]]*$//' file | cat -vet - hello$ bye$ ha$ # tab was removed!

How do I get rid of trailing space in Python?

strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.


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.


At least on Mountain Lion, Viktor's answer will also remove the character 't' when it is at the end of a line. The following fixes that issue:

sed -i '' -e's/[[:space:]]*$//' "$1"

Thanks to codaddict for suggesting the -i option.

The following command solves the problem on Snow Leopard

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

It is best to also quote $1:

sed -i.bak 's/[[:blank:]]*$//' "$1"

var1="\t\t Test String trimming   "
echo $var1
Var2=$(echo "${var1}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')
echo $Var2

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!