It's GNU bash, version 4.4.20(1)-release (x86_64-pc-linux-gnu). I have variable with text in it. For example:
var="this is a variable with some text :)"
now I want to have var2
having the same content but multiple spaces replaced with singe one.
I know we can do it with sed, tr, awk and hundred other ways... but is there a chance to do it with parameter-expansion which bash performs ?
Tried:
var=${var/ / } # replacing 2 spaces with 1, but not much helps
var=${var/[ ]*/ } # this replaces space and whatever follows.... bad idea
var=${var/*( )/} # found this in man bash, whatever it does it still doesnt help me...
var2=$(echo $var)
with hope that echo solves problem - doesnt do the job bcs it doesnt preserve special characters like tab and so on..
I strongly would like to have it solved with something that man bash
offers.
CodePudding user response:
*( )
is an extended glob, which needs to be enabled using shopt -s extglob
before you can use it to match zero or more spaces.
The correct replacement, though, would be to replace one or more spaces ( ( )
) with a single space. You also need to use ${var// ...}
to replace every occurrence of multiple spaces, not just the first one.
$ shopt -s extglob
$ echo "$var"
this is a variable with some text :)
$ echo "${var// ( )/ }"
this is a variable with some text :)