remove whitespace from bash variable

Assuming a variable contains spaces, newlines, and tabs followed by some text, why does this:

${var#"${var%%[![:space:]]*}"}  # strip var of everything 
                                # but whitespace
                                # then remove what's left 
                                # (i.e. the whitespace) from var

remove the white space and leave the text, but this:

${var##[:space:]*}  # strip all whitespace from var

does not?

Answers


If I set var=" This is a test ", both your suggestions do not work; just the leading stuff is removed. Why not use the replace functionality that removes all occurrences of whitespace and not just the first:

 ${var//[[:space:]]}

[:space:] is a character class. It's only valid if it is nested inside another set of [ ].


flolo's answer is documented in the "Parameter Substitution" section of the bash man page. Another source of documentation is the Parameter Substitution section of the Advanced Bash-Scripting Guide. The ABS guide includes basic documentation with excellent example code.


What about $(echo $var)

> a="   123 456  " ; a2="$(echo $a)" ; echo "a=\"${a}\" a2=\"${a2}\""
a="   123 456  " a2="123 456"

Need Your Help

Get and parse JSON in Actionscript

json flash actionscript

What I want to do is make a get request to this URL: http://api.beatport.com/catalog/3/most-popular, which should return some JSON and then parse out certain information from it.

Rails summing the values in a hash thats sorted using Regex

ruby regex select hash inject

I have a query here that involves a few elements, as a result my brain is climbing out my ears. i have a hash that's populated with symbols as keys and numbers as values, the hash is used as both a