trim whitespace?

I'm trying to find a command that will trim the white space off a string.

e.g.


$str = "      stuf    "

$str = trim ( $str )

echo $str // ouput would just be stuf

Thanks, Mark

Oh and stripping out returns, line breaks etc would be nice too.

Here is one way to trim spaces (KSH syntax):

$ str=$(print "$str" | nawk '{gsub(/^[ ]*/,"",$0); gsub(/[ ]*$/,"",$0) ; print }')

You can certainly expand it to eliminate other characters.

echo "      stuf    " | tr -s " " 

OR

echo "      stuf    " | tr -s " " | sed 's/^[ ]//g

echo '[ foo ]' | tr -s ' '
[ foo ]

echo ' foo ]' | tr -s ' ' | sed 's/[1]//g'
foo ]

echo '[ foo bar ]' | tr -s ' '
[ foo bar ]

echo '[ foo bar ]' | tr -d ' '
[foobar]

echo ' foo bar ' | sed 's/^ *//;s/ *$//'
foo bar


  1. ↩︎