Adrian
Adrian

Reputation: 2656

search and replace multi-line text with white space

I am trying to search for some text in a XML file, the text is:

</p_dpopis>
    <IMGURL>

And replace it with:

</p_dpopis>
<p_vyrobce>NONAME</p_vyrobce>
    <IMGURL>

Here is what I tried with perl, without any luck:

perl -0pe 's|</p_dpopis>.*\n.*<IMGURL>|replacement|' myxml.xml

What is wrong here?

Upvotes: 0

Views: 120

Answers (2)

i alarmed alien
i alarmed alien

Reputation: 9520

You're missing a 'global' modifier for your regex, and using \s+ to match any amount of whitespace is much easier than specifying .*\n.*. It's also nicer to send the output to another file, rather than having to deal with it in the terminal window.

perl -0pe 's|</p_dpopis>\s+<IMGURL>|</p_dpopis>\n<p_vyrobce>NONAME</p_vyrobce>\n<IMGURL>|g' myxml.xml > my_new_xml.xml

If you're manipulating XML, it is really better to use a dedicated XML parser -- you can get into all sorts of mischief by manipulating an irregular language such as XML with regular expressions.

Upvotes: 0

zerodiff
zerodiff

Reputation: 1700

Your syntax works:

$ cat file
</p_dpopis>
    <IMGURL>
$ perl -0pe 's|</p_dpopis>.*\n.*<IMGURL>|replacement|g' file
replacement

Here is a sed example with the same example file:

$ sed -r '/<\/p_dpopis>/{ N; s%</p_dpopis>.*\n.*<IMGURL>%replaced\ntest%g }' file
replaced
test

See this reference for more info.

Upvotes: 1

Related Questions