1

I have a large XML file with several tags.

One of the sub tag is as below:

<Products>
  <SubProduct>    ----> this line is problem
    <SubProduct>
        <Name>One</Name>
    </SubProduct>
    <SubProduct>
        <Name>One</Name>
    </SubProduct>
    <SubProduct>
        <Name>One</Name>
    </SubProduct>
    <SubProduct>
        <Name>One</Name>
    </SubProduct>
    <SubProduct>
        <Name>One</Name>
    </SubProduct>
  </SubProduct>   ----> this line is problem
</Products> 

As seen above, the Products tags will have multiple SubProduct tags.

However, an extra SubProduct opening and closing tag is appearing as mentioned above (with comment 'this line is problem').

The solution would be to search for two consecutive open SubProduct tags and two consecutive close SubProduct tags and replace one in each with space.

How can I achieve this using sed?

How can I search for two consecutive tags where the tags are on separate lines as well as I do not know how many spaces will be present between the two consecutive tags (it could be 5 spaces or 10 spaces before or after the new line character).

2
 sed '/<SubProduct>/{N;s/<SubProduct>$//}' filename > filename1

 sed '/<\/SubProduct>/{N;s/<\/SubProduct>$//}' filename1 > filename
  • I edited the answer, added a "$". Did you check it? – Ankit Jan 24 '14 at 12:21
  • Yes. Checked it.. But its still not working.. – Vicky Jan 24 '14 at 12:34
  • Try this: sed '/<SubProduct>/{n;s/<SubProduct>//}' filename > filename1 – Ankit Jan 24 '14 at 13:03
0

Maybe you can rely on the indentation:

grep -Ev '^  </?SubProduct' < file
0

If sed is not an absolute requirement, you could use this Perl script:

perl -ne 'if(/(<.?SubProduct>)/){next if $l=~/$1/} $l=$_; print' file.xml

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.