Answer the question
In order to leave comments, you need to log in
[SOLVED] Sed variable substitution in regular expression
Hello cheaters!
I'm writing a script
There is a variable
ip=xx.xx.xx.xx
I need to replace its value with a string in the file.
I do this
cat /etc/file.conf | sed 's/^IP.*/IPADDRESS=$ip/g' > /etc/file.conf2 && mv /etc/file.conf2 /etc/file.conf
At the output I get
IPADDRESS=$ip
instead
IPADDRESS=xx.xx.xx.xx
Tried to escape "' \ - does not work
Please help, those who have encountered this problem
Thank you in advance.
Answer the question
In order to leave comments, you need to log in
Quotes, well, change the quotes. No `echo`.
And if you have GNU sed, then it has the -i option. Then the command will look like this:
sed -i "s/^IP.*/IPADDRESS=$ip/g" /etc/file.conf
You can also do this:
sed -i 's/^IP.*/IPADDRESS='$ip'/g' /etc/file.conf
If sed is not GNU, then:
sed "s/^IP.*/IPADDRESS=$ip/g" /etc/file.conf > /etc/file.conf2 && mv /etc/file.conf2 /etc/file.conf
Itself suffered with use of variables in a script. The solution is this:
1) quotes are not single, but double.
2) the variable name is enclosed in curly brackets
S1=bla_bla
S2=zlo_zlo
sed -i "s/${S1}/${S2}/g" path_to_my_file
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question