concatenate is ignoring space

Hi All,I am facing the below problem I have set a variable:

a=`cat a.txt| grep "mad" | cut -c 30-50`

the output is coming

echo $a1
10 Mad300 3215

however the actual ouput is

1.10 Mad300     3215

There are 4spaces between 300 and 3215 so if i do:

echo "$a" I am getting correct output:

1.10 Mad300     3215

Now I have to concatenate value of a to some variable $b and assign to $c .

c="$b$a"

So i am not getting the correct value in $c it is having trimmed spaces output.

1.10 Mad300 3215

Please advice why the spaces are trimmed and how to get the correct value in $c variable.

Use double quotes around variables to avoid trimming of spaces. Look at the below example carefully. You'll understand what shell is doing to those extra whitespaces.

[root@host user]# x="hello     world"
[root@host user]# echo $x
hello world
[root@host user]# echo "$x"
hello     world
[root@host user]# y=" earth     mars"
[root@host user]# echo $y
earth mars
[root@host user]# echo "$y"
 earth     mars
[root@host user]# z="$x$y"
[root@host user]# echo $z
hello world earth mars
[root@host user]# echo "$z"
hello     world earth     mars

And please format your post properly. Here's a link on how to use code tags.

1 Like

Nothing obvious wrong. When checking the vaue of $c , remember the quotes:

echo "$c"

For future posts, please mention what Operating System and version you are running and what Shell you are using. Also please use CODE tags to preserve space characters in your posts (which are certainly important to this post).

dont use the cat

 
 
a=$(grep "mad" a.txt | cut -c 30-50)
echo "$a"

you can use awk also

 
awk '/mad/ {print substr($0,30,20)}' a.txt