0

我有两个文件,File1 和 File2。我想比较这两个文件之间的行并打印。但是我找不到匹配特定字符串的方法。我尝试了下面的编码,但它打印出意外的结果。当它与 File1 的名称(例如ldt
)匹配时, 我想打印 File2 数据(例如 b05* ldt * 10ud0e0)。对于 File1 中带有星号 * 的数据(例如 b05can03*n0b5),* 可以是任何字符。为了匹配,它必须匹配File2中*的头部和尾部。因此,它将打印出b05can03un0b5。并且打印必须按照 File1 的顺序。谁能给我这方面的建议?

文件 1

ldt b05dcc00
mny
b05can03
*n0b5
b05mdd04*n9c9

文件2

/* To start: b05afn10ud0b0 */  
/* To start: b05dcc00ud0c0 */  
/* To start: b05ldt10ud0e0 */  
/* To start: b05dcc10ud0i0 */  
/* To start: b05afn10ud0m0 */  
/* To start: b05afn10ud0s0 */  
/* To start: b05mny00ud0b5 */  
/* To start: b05mny00ud0d3 */  
/* To start: b05mdd04un9c9 */  
/* To start: b05ahn00ud0j5 */  
/* To start: b05mny00ud0m7 */  
/* To start: b05can03un0b0 */  
/* To start: b05can03un0b5 */  

编码:

my ( @arr1, @arr2 );

@arr1 = <File1>; 
@arr2 = <File2>;

foreach my $line1 (@arr1) {
    foreach my $line2 (@arr2) {
        if ( $line1 =~ $line2 && $line1 =~ m/^\w+(\W)\w+(.*)/ ) { 
            print "$line2\n";
        }   
    }     
}

预期结果:

b05ldt10ud0e0
b05dcc00ud0c0
b05mny00ud0b5
b05mny00ud0d3
b05mny00ud0m7
b05can03un0b5
b05mdd04un9c9

4

3 回答 3

0

这应该做你想要的......

#!/usr/bin/perl

use strict; 
use warnings;

use autodie;
use feature qw(say);

my $file1 = "f1.txt";
my $file2 = "f2.txt";

open my $fh1, "<", $file1;
open my $fh2, "<", $file2;

my @wanted = map { chomp; qr/$_/; } <$fh1>;
close $fh1;

while (my $line = <$fh2>) {
    chomp $line;
    for my $wanted (@wanted) {
        say "matched: $line" if $line =~ /$wanted/;
    }   
}
close $fh2;
于 2013-09-10T16:08:41.780 回答
0
open my $File1, "<", "File1" or die $!;
open my $File2, "<", "File2" or die $!;

my @arr1 = map {
  s|\s+$||g;
  s|\*|.|g ? qr/($_)/ : qr/(\w*$_\w*)/;
}
<$File1>;

my $str = do { local $/; <$File2> };

print "$_\n" for map $str =~ /$_/g, @arr1;

输出:

b05ldt10ud0e0
b05dcc00ud0c0
b05mny00ud0b5
b05mny00ud0d3
b05mny00ud0m7
b05can03un0b5
b05mdd04un9c9
于 2013-09-10T16:01:12.570 回答
0

如果 File2 不是太大,您可以将其放入一个变量中,然后全局对整个字符串进行有序匹配:

use strict;
use warnings;

my $file2 = do { local $/; local @ARGV = pop; <> };

while (<>) {
    chomp;
    s/\*/./g;
    print "$1\n" while $file2 =~ m!(?:/\*\s+To\s+start:\s+)(.*$_.*)(?:\s+\*/)!g;
}

用法:perl script.pl File1 File2

输出:

b05ldt10ud0e0
b05dcc00ud0c0
b05mny00ud0b5
b05mny00ud0d3
b05mny00ud0m7
b05can03un0b5
b05mdd04un9c9

希望这可以帮助!

于 2013-09-11T05:01:03.957 回答