This is pretty simply done using the sed command. All you have to know is regular expressions.
To remove leading white spaces
sed 's/^ *//g'
To remove trailing white spaces
sed 's/ *$//g'
So as an example,
$ echo " aaaa bbbb " | sed 's/^ *//g' | sed 's/ *$//g' aaaa bbbb