Sed replace variable in double quotes

13,545

Solution 1

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

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

Solution 2

Change your code like his,

sed -i -e 's/name="master"/name="'"$variable"'"/g' test
Share:
13,545
Ken J
Author by

Ken J

Updated on September 15, 2022

Comments

  • Ken J
    Ken J over 1 year

    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?

  • chepner
    chepner over 8 years
    Beware, though, that you'll need to escape characters interpreted specially by sed (such as /) in the value of variable.
  • Toby Speight
    Toby Speight about 7 years
    Am I to presume that you've actually tried that code? Are we to just ignore the fact that you didn't provide a filename for -i nor a syntactically valid sed command?