Suyash
Suyash

Reputation: 625

Replace double quotes and space using sed

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.

Upvotes: 3

Views: 1186

Answers (4)

khachik
khachik

Reputation: 28703

Use sed -i "$1s#.*#\"$replace\"#" $txnFile. Note that it uses # instead of / as a separator for SED, because $replace contains /. Also, the answer by @choroba makes sense. Make sure your code does exactly what you want and does not work "accidently".

Upvotes: 1

guillaume
guillaume

Reputation: 1380

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 
}

Upvotes: 1

Kamil Šrot
Kamil Šrot

Reputation: 2221

Something like the following should work:

replace="<ref bean=\"$3\"\/>"

Note only one backslash (you escape the double quotes) and the backslash before the / character (you escape it for sed to use it as regular character, not the metacharacter used in replace command of sed)

Upvotes: 1

choroba
choroba

Reputation: 242038

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.

Upvotes: 1

Related Questions