Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell variables in sed script

Tags:

sed

The sed command works as expected at the command prompt, but does not work in a shell script.

new_db_name=`echo "$new_db_name" | sed 's/$replace_string/$replace_with/'` 

Why is that, and how can I fix it?

like image 551
shantanuo Avatar asked Aug 10 '11 06:08

shantanuo


People also ask

Can you use variables in sed?

The shell is responsible for expanding variables. When you use single quotes for strings, its contents will be treated literally, so sed now tries to replace every occurrence of the literal $var1 by ZZ .

How do you replace a variable in a file using sed?

How SED Works. In the syntax, you only need to provide a suitable “new string” name that you want to be placed with the “old string”. Of course, the old string name needs to be entered as well. Then, provide the file name in the place of “file_name” from where the old string will be found and replaced.

What are the variables in shell script?

A variable is a character string to which we assign a value. The value assigned could be a number, text, filename, device, or any other type of data. A variable is nothing more than a pointer to the actual data. The shell enables you to create, assign, and delete variables.


Video Answer


2 Answers

Use double quotes for the sed expression.

new_db_name=$(echo "$new_db_name" | sed "s/$replace_string/$replace_with/") 
like image 122
Delan Azabani Avatar answered Sep 23 '22 03:09

Delan Azabani


If you use bash, this should work:

new_db_name=${new_db_name/$replace_string/$replace_with} 
like image 29
glenn jackman Avatar answered Sep 19 '22 03:09

glenn jackman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!