0

I'm trying to replace multiple lines in a text file (an XML element with an unknown number of children) with the contents of a separate text file. I've managed to get the replace mostly working using perl, but it's inserting an additional blank line after the string it replaces that i'd like to get rid of. See below for code showing the perl command as well as the input and replacement files.

Does anybody know how to prevent the additional blank line from appearing? I'm open to using other tools besides perl if necessary.

==> cat test.xml
<root>
<values>
<value>1</value>
<value>2</value>
<value>3</value>
</values>
</root>
==> cat replace.xml
<values>
<value>4</value>
<value>5</value>
</values>
==> perl -i -p0e 's;<values>.*<\/values>;`cat replace.xml`;sge' test.xml
==> cat test.xml
<root>
<values>
<value>4</value>
<value>5</value>
</values>

</root>
==> 
0

2 Answers 2

0

After messing around with this all day i figured it out almost immediately after asking the question on here...

i was able to fix it by including a newline in the search criteria of the perl command. it looks like it was just leaving the newline that was already on the line after the closing xml tag and then adding an additional one from the "cat" command.

perl -i -p0e 's;<values>.*<\/values>\n;`cat replace.xml`;sge' test.xml

Edit: Thanks to mosvy's response i found another solution that will work if the text to be replaced doesn't have a trailing newline as it did in my case:

perl -i -p0e 's;<values>.*<\/values>;`head -c -1 replace.xml`;sge' test.xml

using head instead of cat prevents the output of the additional newline

1
  • That will not work if the ending tag is not followed by a newline. The real answer is that the backquotes/qx/command substitution in perl does not strip trailing newlines, as it does in the shell. Example: perl -e 'printf "{%s}\n", `echo yup`'
    – user313992
    Apr 30, 2019 at 1:58
0
$ perl -00pe '
    chop($r //= join "", <STDIN>);
    s|<values>.*</values>|$r|sg;
  ' test.xml < replace.xml

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .