Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace double quotes and space using sed

Tags:

linux

unix

I'm on rhel5 and have the following problem: I have a function which replaces all the content from a given line with the text i want it to. Everything works fine till i need double quotes to be placed. following is the code:

ReplaceLine()
{
       txnFile="File.xml"
        if [ "$2" == "enable" ];then
                replace="<ref bean=\\"$3\\"/>"
        else
                replace="<!--<ref bean=\\"$3\\"/>-->"
        fi
        sed -i "$1s/.*/$replace/" $txnFile 
}

$1=line number
$2=enable/disable
$3=string to be put

Current code replaces the given line in the file with this:

<ref bean=beginEventBean/>

What i want is this:

<ref bean="beginEventBean"/>

Notice the missing double quotes. Also i used double quotes in sed as without them the spaces in the variables were causing sed to throw errors.

Please help me understand where i'm going the wrong way. Spent hours on this already.

like image 674
Suyash Avatar asked Sep 11 '26 09:09

Suyash


2 Answers

You forgot to escape the forward slash closing the tag. And you put two many slashes.

# one line solution
# sed -i "$1s/.*/<ref bean=\"$3\"\/>/" $txnFile
#                          ^   ^ ^

ReplaceLine()
{
     txnFile="File.xml"
     if [ "$2" == "enable" ];then
            replace="<ref bean=\"$3\"\/>"
     else
            replace="<!--<ref bean=\"$3\"\/>-->"
     fi
     sed -i "$1s/.*/$replace/" $txnFile 
}
like image 138
guillaume Avatar answered Sep 13 '26 23:09

guillaume


Without seeing the source line, I cannot test my solutions. Nevertheless, the following line is definitely not doing what you think:

replace="<ref bean=\\"$3\\"/>"
        ^          ^ ^
        |          | |
start quoted       | |
           backslash |
            end quoted

Add one more backslash, or delete one.

like image 32
choroba Avatar answered Sep 13 '26 22:09

choroba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!