Skip to content

Latest commit

 

History

History
27 lines (17 loc) · 1.31 KB

trim-whitespace-from-variable.md

File metadata and controls

27 lines (17 loc) · 1.31 KB

Trim whitespace from variable

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

Credits

I found that particular sed formulation in this comment to a blog post on the topic of whitespace trimming.


© 2016 Dave Hein

Creative Commons License
This work by Dave Hein is licensed under a Creative Commons Attribution 4.0 International License.