1

I have a xml file

in which the line that needs to be searched is:

SEARCH='<?xml version="1.0" encoding="UTF-8" standalone="no"?><SSC>'

This searched value needs to be replaced with the value in the following variable or can also be stored in another file:

REPLACE='<?xml version="1.0" encoding="UTF-8" standalone="no"?><SSC><ErrorContext><CompatibilityMode>0</CompatibilityMode><ErrorOutput>1</ErrorOutput>.......some more tags.....</MethodContext>
'

How can this be done using unix commands like SED or AWK? (Here SEARCH needs to be replaced with REPLACE.

2
  • The question is not proper.Apologies.
    – tejasw
    Commented Jul 7, 2014 at 9:42
  • 1
    Your input is no well-formed XML. Anyway: Never try to change XML with regular expressions, XML is no regular language and cannot be parsed with regular expressions.
    – Jens Erat
    Commented Jul 7, 2014 at 9:59

2 Answers 2

0

Yes, it could be done with sed, but I agree with Jens. I would recommend using a proper tool like python + lxml library for searching and replacing your tags.

0

As far as I can see the characters to be escaped:

awk '/<\?xml version="1.0" encoding="UTF-8" standalone="no"\?><SSC>/ {print "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><SSC><ErrorContext><CompatibilityMode>0</CompatibilityMode><ErrorOutput>1</ErrorOutput>.......some more tags.....</MethodContext>"}' <<< '<?xml version="1.0" encoding="UTF-8" standalone="no"?><SSC>'
  • in the SEARCH field: you want to escape the ? characters by \?
  • in the REPLACE field: you want to escape the " characters by \"

Or if you need to use variables, also escape " in the SEARCH field and escape the characters twice, once to be stored in a variable and twice to be echoed!

SEARCH_escaped=`sed -e 's/\?/\\\?/g' -e 's/\"/\\\"/g' <<< $SEARCH`
REPLACE_escaped=`sed 's/\"/\\\"/g' <<< $REPLACE`

awk "/$SEARCH_escaped/ {print \"$REPLACE_escaped\"}" <<< $SEARCH

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .