Bash Scripting – Using Bash String Variable in sed

quotingsedshell-script

I'm a relative Linux novice. Suppose that I have a text file a.txt that contains the following text:

A
B
C

Now, if I want to change the text on line 2 (which contains B), I can use the following sed command:

sed -i '2s/^.*$/X/' a.txt

to change the B to X, for example.

But now suppose that I want to write an sed command that changes the text on line 2 to something that includes a bash string variable. I want to change the text on line 2 to fname="myaddress", where the quotation marks are included explicitly, and where myaddress is a bash string variable (defined somewhere else). To try to do this, I have created a bash shell script called mytest.sh and containing the following:

#!/bin/bash

myaddress="/home/"
echo fname=\"$myaddress\"

head a.txt
sed -i '2s/^.*$/fname=\"$myaddress\"/' a.txt
head a.txt

Now, echo fname=\"$myaddress\" prints fname="/home/", which is the text that I want to be on line 2 of a.txt. However, sed instead prints fname="$myaddress" to line 2 of a.txt, probably because it is inside the surrounding apostrophes. In other words, the output of the above bash shell script is:

fname="/home/"
A
B
C

A
fname="$myaddress"
C

My question is, how can I get sed to actually print the value stored in myaddress and referenced by $myaddress?

Best Answer

There are two problems: First, as already noted by Kevin, shell variables need to be enclosed in double quotes if they are to be expanded by the shell. Second, your replacement string contains a /, so you cannot use / at the same time as a delimiter for sed. If you know that some character, say ,, will definitely not occur in the replacement string, you could use that character as sed delimiter, so you get

sed -i '2s,^.*$,fname="'"$myaddress"'",' a.txt
Related Question