J
J
juffinhalli2011-11-10 09:39:07
Regular Expressions
juffinhalli, 2011-11-10 09:39:07

[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

4 answer(s)
@
@sledopit, 2011-11-10
@juffinhalli

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

D
dmitryshiray, 2015-01-16
@dmitryshiray

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

M
mark_ablov, 2011-11-10
@mark_ablov

`echo $ip`?

A
Aleksyk, 2019-11-21
@Aleksyk

sed -is/${ip}//g /etc/postfix/allowip;
Wrote a script for adding, deleting ip of annoying spammers who manage to bypass antispam.
That's just the removal, it works.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question