DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Strip Whitespace From Bash Variable

09.29.2009
| 6844 views |
  • submit to reddit
        Strip (AKA "trim") the whitespace from the beginning and end of a variable in Bash.

# Strip the whitespace from the beginning and end.
STRING_VAR=`expr "$STRING_VAR" : '[[:space:]]*\(.*\)[[:space:]]*$'`

<b>Sources</b>
From <a href="http://booklistgensh.peterknowles.com">Peter Knowles's</a> "booklistgen.sh" script for converting files to Sony Librie format.
<a href="http://www.linuxtopia.org/online_books/advanced_bash_scripting_guide/moreadv.html">Original forum post</a>    

Comments

Snippets Manager replied on Sat, 2009/05/09 - 2:35am

this only strips spaces, not all whitespace: This has worked for me: $stripped_version=`echo $unstripped_version| awk '{gsub(/^ +| +$/,"")}1'`