How to insert a space and assign the value to another variable?

Hello,

I need to insert a space between 2 strings. I used many techniques and all of them worked but when I assign the value to another variable then the inserted space vanishes, strange! Please advise.

# dat=`date |awk '{print $2,$3}'`
# echo $dat
Nov 3

The above is perfectly fine. Now

# echo ${dat}|sed "s/ /  /g"
Nov  3
#

The above also is perfectly fine. Now if I assign the same output to another variable the extra space vanished.

# dat2=`echo ${dat}|sed "s/ /  /g"`
# echo $dat2
Nov 3
#

Please advise how to retain the extra space in the new variable. Sorry if its a basic question but I never noticed such things.

TIA

The shell is stripping your additional space. Quote the $dat2 string to protect it from the shell parameter expansion.

# dat2=`echo "${dat}"|sed "s/ /  /g"`
# echo "$dat2"
Nov  3

You can see this issue even without variables:

# echo one      two     three
one two three

# echo "one      two     three"
one      two     three

It's there. Try double quotes: echo "$dat2"

I cant pm you as i dont have enough post counts, i think i found a way to do my work not sure but worth a try. ill post in short time my work :confused:

You are not supposed to PM technical questions in any case.

1 Like