using Sed to search and replace text in XML file

43,431

The issue is that your search pattern contains / which you are using as the replacement delimiter, you need to use another character for that or escape the /:

sed -i 's#<!--UpdateAccountGUIDs>UpdateAndExit</UpdateAccountGUIDs-->#<UpdateAccountGUIDs>UpdateAndExit</UpdateAccountGUIDs>#' File.XML

or

sed -i 's/<!--UpdateAccountGUIDs>UpdateAndExit<\/UpdateAccountGUIDs-->/<UpdateAccountGUIDs>UpdateAndExit<\/UpdateAccountGUIDs>/' File.XML

Note that you should never use regular expressions to parse [X]HTML.

Finally, as a general rule, when working with regular expressions, less is more. You should try to specify the simplest possible exclusive pattern rather than repeat all text. This not only makes your code much easier to read, it also avoids problems like the one you were facing. For example:

sed -i -r 's/<!--(UpdateAccountGUIDs.+?)-->/<\1>/' File.XML

Here, the -r enables extended regular expression syntax so we can use () to capture a group (without needing to escape the parentheses) and then refer to the captured text as \1. So, the command above simply looks for a comment that is adjacent to UpdateAccountGUIDs, extends till the first end of comment statement and then does the replacement.

Share:
43,431

Related videos on Youtube

terdon
Author by

terdon

Updated on September 18, 2022

Comments

  • terdon
    terdon over 1 year

    I have the following text in File.XML:

    <!--UpdateAccountGUIDs>UpdateAndExit</UpdateAccountGUIDs-->
    

    I would like to replace that with

    <UpdateAccountGUIDs>UpdateAndExit</UpdateAccountGUIDs>
    

    I tried:

    $ sed -i 's/<!--UpdateAccountGUIDs>UpdateAndExit</UpdateAccountGUIDs-->/<UpdateAccountGUIDs>UpdateAndExit</UpdateAccountGUIDs>/' File.XML
    

    But get this error:

    sed: -e expression #1, char 63: unknown option to `s'