0

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!

Jakob Benz
  • 127
  • 1
  • 14
  • Please demonstrate that you are attempting to gain an understanding of the problem by providing an example if what you have already tried. – Terry Burton Feb 15 '16 at 20:22

2 Answers2

1

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 ;
choroba
  • 231,213
  • 25
  • 204
  • 289
  • Obligatory link to what happens when you try to use regex to parse XML or HTML: http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – mscha Feb 16 '16 at 00:26
  • While I agree generally, he did not actually ask for *parsing* the HTML, i.e. getting info out of it. – Jan Feb 16 '16 at 06:39
  • @Jan: The point is you can't reliably modify an XML document without parsing it. – choroba Feb 16 '16 at 08:44
0

You could come up with:

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

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

Jan
  • 42,290
  • 8
  • 54
  • 79