Perl替换xml文件中的一些内容

时间:2015-12-02 07:35:21

标签: perl

我是Perl的新手。现在我尝试使用Perl替换xml文件中的某些内容。以下代码是我的命令

perl -pi -e "s/<Connector port=\"\d+\" protocol=\"HTTP/1.1\" /<Connector port=\"${ACCESS_PORT}\" protocol=\"HTTP/1.1\" /g" $TOMCAT_SERVER_CONF

但perl抱怨这个:

Bareword found where operator expected at -e line 1, near ""34233" protocol"
(Missing operator before protocol?)
Can't modify numeric lt (<) in scalar assignment at -e line 1, near ""34233" protocol"
syntax error at -e line 1, near ""34233" protocol"
Execution of -e aborted due to compilation errors.

有人可以帮忙吗?我会非常感激的。

2 个答案:

答案 0 :(得分:1)

你必须在命令1.1之前转义正斜杠(实际上你的命令中有两个相同的东西)。因为您使用/作为正则表达式分隔符。

\"HTTP\/1.1\"
      ^ here

或者,您也可以使用任何不同的正则表达式分隔符。例如,使用hash

s#..regex..#;;replace;;#g

答案 1 :(得分:1)

不要使用正则表达式来解析XML。这很讨厌。改为使用解析器:

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

use XML::Twig; 

my $twig = XML::Twig -> parsefile ( $ENV{'TOMCAT_SERVER_CONF'} ); 
foreach my $connector ( $twig -> get_xpath('Connector') ) {
    $connector -> set_att('port', $ENV{'ACCESS_PORT'} ); 
}
$twig -> print;

如果您需要就地编辑:

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

use XML::Twig;

sub mod_connector {
    my ( $twig, $connector ) = @_;
    $connector->set_att( 'port', $ENV{'ACCESS_PORT'} );
}

my $twig = XML::Twig->new( twig_handlers => { 'Connector' => \&mod_connector } );
   $twig -> parsefile_inplace( $ENV{'TOMCAT_ACCESS_CONF'} );

如果你真的想要一个班轮:

perl -MXML::Twig -e 'XML::Twig->new( twig_handlers => { Connector => sub { $_->set_att( "port", $ENV{ACCESS_PORT} ) }})->parsefile_inplace( $ENV{TOMCAT_ACCESS_CONF} );'
相关问题