Jakob Benz
Jakob Benz

Reputation: 127

Replace multiline string by multiline string using perl

I'm trying to edit a tomcat configuration file using perl. I want to uncomment the following lines in an xml file. I tried it with perl, but it won't work.

<!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
               maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
-->

This is what i got:

perl -i -pe 's~<!--\n    <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"\n              maxThreads="150" SSLEnabled="true" scheme="https" secure="true"\n              clientAuth="false" sslProtocol="TLS" />\n    -->~<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"\n              maxThreads="150" SSLEnabled="true" scheme="https" secure="true"\n              clientAuth="false" sslProtocol="TLS" />~' $CATALINA_HOME/conf/server.xml

Another question: can i find and replace a string with a regex?

Thanks for any help!

Upvotes: 0

Views: 163

Answers (2)

choroba
choroba

Reputation: 241858

Regular expression is not the right tool to modify XML. Use an XML aware library. For example, XML::LibXML:

#! /usr/bin/perl
use warnings;
use strict;

use XML::LibXML;

my $xml     = 'XML::LibXML'->load_xml(location => 'file.xml');
my $comment = $xml->findnodes('//comment()')->[0];
my $inner   = 'XML::LibXML'->load_xml(string => $comment->textContent)
              ->getFirstChild;
$comment->replaceNode($inner);
print $xml;

Or shorter with the xsh wrapper:

open file.xml ;
xinsert chunk string(//comment()[1]) replace //comment()[1] ;
save :b ;

Upvotes: 1

Jan
Jan

Reputation: 43169

You could come up with:

~^(<!--.*\R)(\s+<Connector[^>]+>)(.*\R-->.*)~

And replace the match with the second group, see a demo here on regex101.com.

Upvotes: 0

Related Questions