1

For the replacement of string between two patterns i use:

String i want to change: <name>FOO</name>
I use for this:

s#(<name>).*?(</name)#\1xxxxxxxxxxx\2#g;

I'm looking for solution, when 1st patters exist in two lines:

<attributes>
      <name>AUTOR</name>
      <value>FOO</value>
      <type>1</type>
 </attributes>

I want to replace BAR I've tried something like this, but with no results:

s#(AUTOR</name>\n\r<value>).*?(</value)#\1xxxxxxxxxxx\2#g;

EDIT: I was convinced to use XMLStarlet instead of SED.

Blue
  • 22,608
  • 7
  • 62
  • 92
Fangir
  • 131
  • 6
  • 16
  • 4
    If you give us a valid XML file, we can give you a solution that uses an XML parser to do this. The `sed` utility is inappropriate for parsing and modifying XML data. – Kusalananda Jul 14 '16 at 07:26
  • 2
    [Obligatory link](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) to the famous StackOverflow post about this. – Tom Lord Jul 14 '16 at 08:18

1 Answers1

1

Line-oriented tools are generally inappropriate for parsing and modifying XML data. Instead of sed, consider using something like XMLStarlet.

Using XMLStarlet:

$ cat data.xml
<attributes>
      <name>AUTOR</name>
      <value>FOO</value>
      <type>1</type>
 </attributes>

$ xml ed -u '/attributes/value' -v NEWFOO data.xml
<?xml version="1.0"?>
<attributes>
  <name>AUTOR</name>
  <value>NEWFOO</value>
  <type>1</type>
</attributes>

If you have a more interesting XML:

<books>
  <book>
    <attributes>
      <name>Author 1</name>
      <value>FOO</value>
      <type>1</type>
    </attributes>
  </book>
  <book>
    <attributes>
      <name>Author 2</name>
      <value>FOO</value>
      <type>1</type>
    </attributes>
  </book>
</books>

.. and you would like to change FOO for only "Author 2", then

$ xml ed -u '//attributes[name="Author 2"]/value' -v NEWFOO data.xml
<?xml version="1.0"?>
<books>
  <book>
    <attributes>
      <name>Author 1</name>
      <value>FOO</value>
      <type>1</type>
    </attributes>
  </book>
  <book>
    <attributes>
      <name>Author 2</name>
      <value>NEWFOO</value>
      <type>1</type>
    </attributes>
  </book>
</books>
Kusalananda
  • 14,885
  • 3
  • 41
  • 52