How to replace a line in an xml file with a set of lines stored in a variable or file using unix commands?

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.

tejasw

Posted 2014-07-07T09:33:39.003

Reputation: 11

The question is not proper.Apologies. – tejasw – 2014-07-07T09:42:31.320

1Your 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 – 2014-07-07T09:59:52.333

Answers

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

Sébastien Guarnay

Posted 2014-07-07T09:33:39.003

Reputation: 21

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.

loluengo

Posted 2014-07-07T09:33:39.003

Reputation: 111