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

  • 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:]]*$'`

From <a href="">Peter Knowles's</a> "" script for converting files to Sony Librie format.
<a href="">Original forum post</a>    


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'`