Replacing $ in variable

hi
I have a variable like

k=$DESTDIR/$PKG/$VERSION

I want to replace each $ in string k with say "XXX".
so that k becomes like this "XXXDESTDIR/XXXPKG/XXXVERSION"

when I use echo $k | sed -e "s/\$/XXX" it actually passes expanded of variables $DESTDIR, $PKG and $VERSION to sed.

Please help.

Ashish

hi
I have a variable like

k=$DESTDIR/$PKG/$VERSION

I want to replace each $ in string k with say "XXX".
so that k becomes like this "XXXDESTDIR/XXXPKG/XXXVERSION"

when I use echo $k | sed -e "s/\$/XXX" it actually passes expanded of variables $DESTDIR, $PKG and $VERSION to sed.

Please help.

probably the variable k is not formed correctly. Can you try echo $k and see if you get $DESTDIR/$PKG/$VERSION ? Are you forming the variable k like this : k="\$DESTDIR/\$PKG/\$VERSION" ? if so, the sed command works as expected.

$DESTDIR/$PKG/$VERSION is coming from a read only file to k while reading.

then, you need to see how to read it into k by escaping the $. can you tell us how you are reading it from the file and assigning to k ?

I am using while loop like

while read k

.....// if $DESTDIR is present in k then go to next line in file
because DESTDIR is not defined .
else
use value of k as it is it may be $PKG/$VERSION
as these variable are defined.

.....
done < $file

when you do 'echo $k', do you see the shell variables expanded ?
I feel that you need to escape $ by adding '\' everytime you append it to k.

you need to quote to avoid expansion, and your sed is a little out:

 echo '$DESTDIR/$PKG/$VERSION' | sed -e "s/\\$/XXX/g"
XXXDESTDIR/XXXPKG/XXXVERSION

yes i see ...expanded variables when i do "echo $k".
To escape $ first i need to replace "$" with "\$".. thats the problem I am facing.

ok. you can turn off variable expansion by having the string in single quotes:
k='$a$b'
echo $k --> returns $a$b
please try to form the string as above.

It works ...
But I have like this
k=$a$b

Now I want to manipulate this.

If you tell me how to convert it into '$a$b' ... then I will be greatful.