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

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

Trim white space from the right of a string

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

Trim white space from the left of a string

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

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

  1. 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)

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