Tested on OS X El Capitan (10.11.6).
Some commands produce results with undesirable whitespace. For example the wc
command produces leading white space, e.g.:
$ echo "one two three" | wc -w
3
The most portable way to trim leading and trailing whitespace is to use sed
like this: echo $var | sed -e 's/^ *//' -e 's/ *$//'
. For example:
$ echo "one two three" | wc -w | sed -e 's/^ *//' -e 's/ *$//'
3
I found that particular sed
formulation in this comment to a blog post on the topic of whitespace trimming.
© 2016 Dave Hein
This work by Dave Hein is licensed under a Creative Commons Attribution 4.0 International License.