views:

75

answers:

3

i am using the below code for replacing a string inside a shell script.

echo $LINE|sed -e 's/12345678/"$replace"/g'

but its getting replaced with $replace instead of the value of that variable.

could anybody tell what went wrong.

+2  A: 

If you want to interpret $replace, you should not use single quotes since they prevent variable substitution.

Try:

echo $LINE | sed -e "s/12345678/\"${replace}\"/g"

assuming you want the quotes put in. If you don't want the quotes, use:

echo $LINE | sed -e "s/12345678/${replace}/g"

Transcript:

pax> export replace=987654321
pax> echo X123456789X | sed "s/123456789/${replace}/"
X987654321X
pax> _

Just be careful to ensure that ${replace} doesn't have any characters of significance to sed (like / for instance) since it will cause confusion unless escaped. But if, as you say, you're replacing one number with another, that shouldn't be a problem.

paxdiablo
i dont want the quotes put in.i want one number to be replaced with other
Vijay Sarathi
`export` is not necessary.
Dennis Williamson
I usually always use `export` to ensure that variables are set for children but, as you say, you could just as easily use `set` here. However, the `export/set` choice is irrelevant here, a style issue, and has no effect on the actual answer.
paxdiablo
paxdiablo: `set` is also not necessary (and how were you going to use it anyway?). Just `replace=987654321`.
Roman Cheplyaka
A: 
echo $LINE | sed -e 's/12345678/'$replace'/g'

you can still use single quotes, but you have to "open" them when you want the variable expanded at the right place. otherwise the string is taken "literally" (as @paxdiablo correctly stated, his answer is correct as well)

akira
+1  A: 

you can use the shell (bash/ksh).

$ var="12345678abc"
$ replace="test"
$ echo ${var//12345678/$replace}
testabc
ghostdog74
May want to mention that's bash-specific (and ksh?). Probably not of import to most people but some of us are still forced to work on ancient UNIXen :-)
paxdiablo