Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a string in shell script using a variable

Tags:

shell

unix

sed

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?

like image 721
Vijay Avatar asked Jul 22 '10 05:07

Vijay


People also ask

How do I replace a string in a string in shell script?

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.

What is $_ in shell script?

$_ (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.

What does ${} mean in shell script?

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.


1 Answers

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.

like image 188
paxdiablo Avatar answered Sep 21 '22 12:09

paxdiablo