LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Sed not accepting variable in line replacement (https://www.linuxquestions.org/questions/linux-newbie-8/sed-not-accepting-variable-in-line-replacement-937524/)

qweeak 04-01-2012 06:15 AM

Sed not accepting variable in line replacement
 
Hi Guys,

I'm doing a line replacement operation and sed is not accepting any variable. This is my script
----
i=10.10.10.1
sed '5 c\IPADDR=$i\' test
----

I tried a-lot of variation like using "". None is working. Any suggestions guys

sycamorex 04-01-2012 07:11 AM

Try:
Code:

sed "3 c\IPADDR=$i\\" test
You need to escape the closing backslash.

catkin 04-01-2012 07:22 AM

Double quotes are required and the . means any single character so you want to escape it if you exactly want to match the IP address. Starting with the simpler case of not addressing a specific line and substituting the match, does this work:
Code:

i='10\.10\.10\.1'
sed "s/IPADDR=$i/XXX/" test


qweeak 04-01-2012 07:36 AM

Hi Guys,

Thanks sycamorex. That did the trick. Can you tell how it is escaped here.

sycamorex 04-01-2012 07:46 AM

Quote:

Originally Posted by qweeak (Post 4641932)
Hi Guys,

Thanks sycamorex. That did the trick. Can you tell how it is escaped here.

In order to evaluate any variable you need to enclose the whole expression in double quotes. If you do it, any backslash will be interpreted as an attempt to escape the character following it so in your original string

Code:

$i\"
the backslash's function was to escape the closing double quote (not what we want) and the sed was looking for a closing backslash

Code:

c\......\
If we escape the backslash

Code:

\\"
the first backslash will escape the second so the second one will be treated literally as a backslash, which is what sed/regex was looking for to evaluate the whole expression.

I hope that makes sense to you:)

qweeak 04-01-2012 08:07 AM

Hello,

Wow.. i never though of that. That makes sense. Thanks sycamorex.


All times are GMT -5. The time now is 07:45 AM.