Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove whitespace from bash variable

Tags:

bash

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?

like image 888
MCS Avatar asked Nov 27 '08 16:11

MCS


1 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:]]}
like image 187
flolo Avatar answered Oct 13 '22 00:10

flolo