user1651888
user1651888

Reputation: 463

Find and Replace string using sed gives error

I am using shell script. My requirement is to find and replace the string. The string contains "/" char as well. I am getting error sed: -e expression #1, char 18: unterminated `s' command. Can someone tell how should i replace the string which has "/"?

#!/bin/bash
...
search_string="../conf/TestSystem/Inst1.xml"
rep="Inst1/Instrument.xml"

sed -i 's|${line}|${rep}/g' MasterConfiguration.xml

I tried using another sed command but that one also gave error sed: -e expression #1, char 13: unknown option to `s'

sed -e "s/${line}/${rep}/g" MasterConfiguration.xml > tempfile

Upvotes: 1

Views: 1142

Answers (2)

KeyNone
KeyNone

Reputation: 9190

Whenever you deal with shell-variables you have to get them out of the "sed-string":

For example:

sed -e "s/"${line}"/"${rep}"/g" MasterConfiguration.xml > tempfile

Otherwise sed will treat the chars as-is and search for ${line} literally: enter image description here
As you see, nothing happens here.

Furthermore, if your variables contain / you need to use another delimiter for sed. I tend to use ~ in such a case, but you're free to use other chars - just be consequent and don't mix them like in your first example-sed-command:

sed 's~'${line}'~'${rep}'/g' //WRONG
sed 's~'${line}'~'${rep}'~g' //RIGHT

Combine both and it will work: enter image description here

Upvotes: 1

sat
sat

Reputation: 14979

You can try this sed,

sed -i "s#${line}#${rep}#g" MasterConfiguration.xml

Problem:

Instead you have,

sed -i "s|${line}|${rep}/g" MasterConfiguration.xml

It should be,

sed -i "s|${line}|${rep}|g" MasterConfiguration.xml

Syntax:

sed "s|pattern|replacement|g"

Upvotes: 0

Related Questions