Using a variable inside ’sed’

I have declared a variable in a file. I want to set the value of this variable, to a variable in a different file. When I tried to use ’sed’ to accomplish this, I encountered an error. The error was, its not getting the value from the old file and just places the variable name in the new file. By changing the command slightly, It works fine. Given below are the commands I used.

OLD-FILE

a=one

NEW-FILE

b=four

$ source OLD-FILE

$ sed -i ’s/b=.*/b=\${a}/’ NEW-FILE    #Output : b=${a}  #Wrong

$ sed -i ’s/b=.*/b=’$a/ NEW-FILE         #Output : b=one    #Correct One

Published in: on August 9, 2007 at 8:00 pm Comments (4)

The URI to TrackBack this entry is: http://rsubramani.wordpress.com/2007/08/09/using-a-variable-inside-sed/trackback/

RSS feed for comments on this post.

4 Comments Leave a comment.

  1. very interesting, but I don’t agree with you
    Idetrorce

  2. I faced this problem and google search got me here.. thanks da sombai :-)

  3. this works:
    a=”hello”
    sed -e s/b=.*/b=”$a”/ OLDFILE

    do not using -e ’something’ ,while use “” to include the variable

  4. This was exactly what I needed.

    MSG2=`echo ${MSG1} | sed ’s/$A/’${START}/g | sed ’s/$B/’${STOP}/g`
    echo “${MSG2}”

    Now prints exactly what I intended instead of variable names.

    Thanks!


Leave a Comment