Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed replace variable in double quotes

Tags:

regex

bash

sed

I've created a bash script that takes a parameter. I want to pass that parameter to sed to replace an existing string with another which is composed of the variable:

variable=$1
echo $variable
sed -i -e 's/name="master"/name="$variable"/g' test

The problem is that the script is not replacing $variable with the parameter, it's just replacing the string with "$variable":

<host name=""$variable"" xmlns="urn:jboss:domain:3:0:>

How can I replace a string in quotes with the variable?

like image 730
Ken J Avatar asked Jul 29 '15 18:07

Ken J


People also ask

Does SED work with double quotes?

@DummyHead Here's another approach: if you use single quotes, the sed command is exactly as you type it. If you use double quotes, you must take into account all shell substitutions and elaborations to "visualize" what command is eventually passed on to sed.

How do you use double quotes in a variable?

When referencing a variable, it is generally advisable to enclose its name in double quotes. This prevents reinterpretation of all special characters within the quoted string -- except $, ` (backquote), and \ (escape).

When to use double quotes in bash?

Double quotes can be used to for strings that contain spaces in your Bash script. Take a look at the following example where we store a space inside of a variable. Since there is a space between the two words, it is necessary to wrap the whole string in quotes.


1 Answers

Variable expansion does not happen within single quotes. Do it in double quotes:

sed -i -e 's/name="master"/name="'"$variable"'"/g' test
like image 86
Sven Marnach Avatar answered Nov 12 '22 14:11

Sven Marnach