sed and special character in data

I have a script that is reading an existing report, pulling out the customer code, then tacking on the customer name from another file and replacing the existing customer code with the new field. This was written for me by someone else. I'm not real familiar with sed.

The data is getting into the variables correctly, but if the customer name contains a "&" sign, then it repeats the first variable.

My statements are

y=`echo $a$b$i`
z=`echo $a$b$i$b$x`
sed s/"$y "/"$z "/g a.txt > CusT_TmP
cat CusT_TmP a.txt

When I run the script I get back
a=CUST-CD:
b=" "
i=123456
x= W & B

y=CUST-CD: 123456
z=CUST-CD: 123456 W & B Corp

But the entry in the output comes out like

CUST-CD 123456 W CUST-CD 123456 B Corp

Any customer name that I have an & in the name does this.

Any ideas of how to fix this?
Thanks

sed treats & as the pattern space - in other words what sed found as a match for your regular expression. & as an operator means "print the pattern space".

One workaround without doing a lot of sed hacking is to change the & character to something else, then change it back using tr:

tr '&' '+' < a.txt > tmpfile
y=`echo $a$b$i`
z=`echo $a$b$i$b$x`
sed s/"$y "/"$z "/g tmpfile | tr '+' '&' > CusT_TmP
cat CusT_TmP a.txt

HM. That sounds like on the right track, but its not working. :frowning:

I used that idea against the customer name file and just left it like that into the output file.
The I re-translated the output file back and it works!
Thanks!