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?