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?
@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.
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).
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.
Variable expansion does not happen within single quotes. Do it in double quotes:
sed -i -e 's/name="master"/name="'"$variable"'"/g' test
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