Trimming White Space with Sed

You can use the following sed commands to trim white space from lines of text:

Trim white space from both sides of a string

echo ' abc ' | sed 's/^ *//;s/ *$//'

Trim white space from the right of a string

echo ' abc ' | sed 's/*//;s/ *$//'

Trim white space from the left of a string

echo ' abc ' | sed 's/^ *//;s/$//'

Trim white space from both ends of every line in a file (keeping a .bak backup)

sed -i.bak 's/^ *//;s/ *$//' file.txt

Trim white space from both ends of every line of every file in the current directory (keeping a .bak backup)

ls -1 | while read line; do cat $line | sed -i.bak 's/^ *//;s/ *$//' $line