delete spaces in the variable in unix script?

Hi All, I need your help.I want to know how to delete the spaces in a variable in unix scripting.Please give solution to this probelm...
thanks ! :confused:

sun:/home/# var="test a string"
sun:/home/# echo $var | sed -e "s/ //g"
testastring

With bash or ksh93:

$var="Test String"
$var=${var/ /}
$echo $var
TestString
var=$( echo "$var" | tr -d ' ' )

or

var=$( echo "$var" | sed "s/ //g" )

Unless you are using sh, go with tayyabq8's suggestion. It is more efficient than the others.

but it did not work if there's another word (or have i missed something): eg

sun:/home/# var="Test String here"
sun:/home/# var=${var/ /}
sun:/home/# echo $var
TestString here

i am using bash.

That syntax only removes one space. But you could loop:

bash-3.00$ v="one two three"
bash-3.00$ v=${v/ /}
bash-3.00$ echo $v
onetwo three
bash-3.00$ v="one two three"
bash-3.00$ while [[ $v == *\ * ]] ; do v=${v/ /} ; done
bash-3.00$ echo $v
onetwothree
bash-3.00$

In any version of ksh you can use some ugly syntax to remove the first or last space. And again you can loop to remove all spaces...

$ v="one two three"
$ v=${v%${v##+([! ])}}${v#${v%${v##+([! ])}} }
$ echo $v
onetwo three
$ v="one two three"
$ v=${v% ${v#${v%%+([! ])}}}${v#${v%%+([! ])}}
$ echo $v
one twothree
$
$
$ v="one two three"
$ while [[ $v == *\ * ]] ; do v=${v%${v##+([! ])}}${v#${v%${v##+([! ])}} } ; done
$ echo $v
onetwothree
$

$ var="one two"

$ printf "%s" $var
onetwo

Note: with most of the versions of printf you'll not get the final new line.

Regards
Dimitre

$ v="one two three four five six"

$ v=${v// /} && echo $v
onetwothreefourfivesix

Regards
Dimitre

Dimetre,

Can you pls explain : v=${v// /}

Variable Expansion

${variable//pattern1/pattern2} replace all occurrences of pattern1 with pattern2 in variable

Regards
Dimitre

Dimitre, Thanks for the explanation.

Perderabo, Can you pls explain this condition construct also: [[ $v == *\ * ]]

Regards,
Tayyab

See Perderabo's last reply in String extraction from user input - sh

Got that, thanks Vino.

Thank you All !
You guyz are too good. thanks again to all those posted the replies.
Thanks!My doubt got cleared.Hope you all support this forum ever.