【问题标题】:Compare and replace two files in perl比较和替换perl中的两个文件
【发布时间】:2013-05-16 17:50:04
【问题描述】:

我正在尝试比较两个文档 test1、test 2 中的字符串

测试 1:

 <p><imagedata rid="rId7"></p>
  ...
 <p><imagedata rid="rId8"></p>

测试2:

<imagesource Id="rId7" Target="image/image1.jpg"/>
...
<imagesource Id="rId9" Target="image/image2.jpg"/>
...
<imagesource Id="rId8" Target="image/image3.jpg"/>

我想要的是,第一个文件应该被替换为图像目标路径,例如:

 <p><imagedata src="image/image1.jpg"></p>
  ...
 <p><imagedata rid="image/image3.jpg"></p>

我试图从两个文件中提取文本,但我坚持比较两个字符串

 opendir(DIR, $filenamenew1);

 our(@test1,@test2);

 open fhr, "$filenamenew1/test1.txt";

 open fhr1, "$filenamenew1/test2.txt";


 my @line;

 @line= <fhr>;

 for (my $i=0;$i<=$#line;$i++)
 {
 if ($line[$i]=~m/rid="(rId[0-9])"/)
 {
 my $k = $1;

 push (@test1, "$k");
 }
 }


 my @file2;

 @file2= <fhr1>;

 for (my $i=0;$i<=$#file2;$i++)
 {
 if ($file2[$i]=~m/Id="(rId[0-9])"/)
 {
 my $k1 = $1;

 push (@test2, "$k1");


 foreach (@test1 = @test2)
 {
 print "equal";
 }

 }

 }

【问题讨论】:

    标签: perl


    【解决方案1】:

    一种解决方案是先读取带有&lt;imagesources&gt; 的文件,然后将ridtarget 保存在哈希中。之后逐行读取另一个文件并比较 rid 是否存在于哈希中并进行替换,例如:

    script.pl的内容:

    #!/usr/bin/env perl
    
    use warnings;
    use strict;
    
    my (%hash);
    
    open my $fh2, '<', shift or die;
    open my $fh1, '<', shift or die;
    
    while ( <$fh2> ) {
            chomp;
            if ( m/Id="(rId\d+)".*Target="([^"]*)"/i ) {
                    $hash{ $1 } = $2;
            }
    }
    
    while ( <$fh1> ) {
            if ( m/rId="([^"]+)"/i && defined $hash{ $1 } ) {
                    s//src="$hash{ $1 }"/;
            }
            print $_;
    }
    

    像这样运行它:

    perl script.pl test2 test1
    

    产生:

    <p><imagedata src="image/image1.jpg"></p>
     ...
    <p><imagedata src="image/image3.jpg"></p>
    

    【讨论】:

    • @VSenthil:您必须将文件作为参数传递,将test2test1 替换为文件系统中的正确路径。或者在源代码中对它们进行硬编码,用这些路径替换 shift() 函数。无论对您来说更容易。
    猜你喜欢
    • 2014-02-16
    • 2015-07-08
    • 2018-09-05
    • 2014-06-14
    • 2014-05-31
    • 1970-01-01
    • 2020-01-11
    • 2018-08-17
    • 2012-03-18
    相关资源
    最近更新 更多