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

 

2 comments

  1. Why not sed -i?

    Also, using xargs would be a bit more efficient than a while loop, as sed would only be run once.

  2. Updated to use -i and make a backup.

    Can you give an example of using xargs?

Leave a Reply

Your email address will not be published. Required fields are marked *