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 $replace
instead of the value of that variable.
Could anybody tell what went wrong?
To replace a substring with new value in a string in Bash Script, we can use sed command. sed stands for stream editor and can be used for find and replace operation. We can specify to sed command whether to replace the first occurrence or all occurrences of the substring in the string.
$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.
Here are all the ways in which variables are substituted in Shell: ${variable} This command substitutes the value of the variable. ${variable:-word} If a variable is null or if it is not set, word is substituted for variable.
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With