2015-12-02 81 views
-1

我是Perl的新手。現在我試圖用Perl來替換xml文件中的某些內容。下面的代碼是我的命令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. 

任何人都可以幫忙嗎?將非常感激它。

回答

1

你必須在你的命令1.1之前轉義正斜槓(事實上在你的命令中有兩個相同的東西)。因爲您正在使用/作爲正則表達式分隔符。

\"HTTP\/1.1\" 
    ^here 

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

s#..regex..#;;replace;;#g 
+0

非常感謝!有用。 – spark1631

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});'