8

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?

4 Answers 4

27

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:]]}
Sign up to request clarification or add additional context in comments.

Comments

4

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

2 Comments

Thanks - I didn't know that character classes required nested brackets.
@MCS - This is documented in regex(7) ("man 7 regex" to read it). Most modern regex implementations include support for the POSIX named character classes, so you can read about them in perl's perlre man page, for example, as well.
1

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.

Comments

0

What about $(echo $var)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.