perl替代多行

时间:2010-10-26 13:28:54

标签: perl matching substitution

我有一个看起来像的文件:

<QUERY name="Secondary">
            <SQLStmt>select * from my_tb;
            </SQLStmt>
<QUERY name="primary">
            <SQLStmt>select * from my_tb;
            </SQLStmt>

<QUERY name="last">
            <SQLStmt>select * from my_tb;
            </SQLStmt>

我需要将SQLStmnts替换为我从命令行收到的其他一些SQLStmnts和Query名称。

如何使用条件匹配和替换?

$qury_nm=shift;
$sqlstmt=shift;
undef $/;
if(/<QUERY name="$qury_nm">(.*)<SQLStmt>(.*)<\SQLStmt>/)
{
  #need help here!!
   substitute the matched qury_nms SQLStmt wth the $sqlstmt and write it into the same file...
}

2 个答案:

答案 0 :(得分:2)

XML不是常规语言。 You should not treat it as such。使用Perl可用的精细XML解析器之一。一个好方法可能是使用XML :: Twig。这是一个教程:http://www.xml.com/pub/a/2001/03/21/xmltwig.html

答案 1 :(得分:0)

这是一种方法:

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

my $qury_nm = 'primary';
my $sqlstmt = 'SELECT col1,col2 FROM table2';
undef $/;
my $str = <DATA>;

$str =~ s!(<QUERY name="$qury_nm">.*?<SQLStmt>).*?(</SQLStmt>)!$1$sqlstmt$2!s;
say $str;

__DATA__
<QUERY name="Secondary">
            <SQLStmt>select * from my_tb;
            </SQLStmt>
<QUERY name="primary">
            <SQLStmt>select * from my_tb;
            </SQLStmt>

<QUERY name="last">
            <SQLStmt>select * from my_tb;
            </SQLStmt>

输出:

<QUERY name="Secondary">
            <SQLStmt>select * from my_tb;
            </SQLStmt>
<QUERY name="primary">
            <SQLStmt>SELECT col1,col2 FROM table2</SQLStmt>

<QUERY name="last">
            <SQLStmt>select * from my_tb;
            </SQLStmt>