Vijay Vijay - 1 year ago 132
Bash Question

Replace a string in shell script using a variable

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

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

but it's getting replaced with
instead of the value of that variable.

Could anybody tell what went wrong?

Answer Source

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


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"


pax> export replace=987654321
pax> echo X123456789X | sed "s/123456789/${replace}/"
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download