2012-08-01 75 views
0

我有两个文件,分别是a.txtb.txt。我的任务是搜索b.txt中的所有字符串a.txt。如果我在a.txtb.txt的字符串之间有任何匹配,那么我想要从文件b.txt中打印对应于该字符串的行以及它的下一行。如何提取一个匹配字符串和下一行的行?

我一直在尝试下面提到的代码,但问题是它不打印任何东西。你能否指出我的问题并提出解决方法?

open fh, "<", "b.txt" or die $!; 
open fh1, "<", "a.txt" or die $!; 

my $array1 = < fh>; 
my $array2 = < fh1>; 

while (my $array1 = < fh>) { 
    if ($array1 =~ m/$array2/i) { 
     print $array1; 
     print scalar < fh>; 
    } 
} 

回答

1

尝试这样的事情

open fh, "<", "b.txt" or die $!; 
open fh1, "<", "a.txt" or die $!; 

while(my $item1 = <fh>) 
{ 
    while(my $item2 = <fh1>) 
    { 
     if($item1 =~ m/$item2/i) 
     { 
      print $item1; 
      print <fh>; 
     } 
    } 

    seek fh1, 0, 0; 
} 

close fh; 
close fh1; 
+0

非常感谢BSen,它的工作原理但是,一旦a.txt的第一个元素被搜索到了,我想将匹配的数据打印到另一个文件中。即在a1.txt中搜索到的第一个元素,在a2.txt中搜索的第二个元素,从而出现。目前你的帮助我能够将所有元素保存在一个文件中。 – 2012-08-01 06:51:33

+0

你能否帮我修改你给出的代码来完成我上面评论中提到的任务 – 2012-08-03 00:26:34

+0

如果我明白你想要什么,那么在循环外添加一个变量,在每次匹配时增加一个变量并打开句柄到新文件(使用变量形成名称,例如a1,a2 ...),然后写入并关闭它 – BSen 2012-08-03 05:49:46

-1

我可以帮助你获得两个数组的元素,我didt了解如何ü要打印的匹配和未来元素,

use Data::Dumper; 
open(FH, "<$file") or die "$!"; 
open(FH1, "<$file1") or die "$!"; 
my @array1 ; 
my @array2 ; 


while(<FH>) { 
    chomp($_); 
    push @array1,$_; 
} 
while(<FH1>) { 
    chomp($_); 
    push @array2,$_; 
} 
close(FH); 
close(FH1); 
print Dumper(@array1); 
print Dumper(@array2); 
0

这里是显而易见的:

use strict; 
use warnings; 

my $line1; 
my $line2; 
my $fh; 
my $fh1; 
my $counter; 

open $fh, "<", "b.txt" or die $!; 
open $fh1, "<", "a.txt" or die $!; 

my @b = <$fh>; 
my @a = <$fh1>; 

for (@b) 
{ 
    $line1 = $_; 
    for (@a) 
    { 
     $line2 = $_; 
     if ($line1 =~ /^$line2$/) 
     { 
      $counter++; 
      open $outfile, ">", "a_${counter}.txt"; 
      print $outfile $line2; 
      close $outfile; 
     } 
    } 
} 

我真的不明白的是你想用scalar做什么?

+0

非常感谢你Hameed.It工程但一旦a.txt的第一个元素已被搜索,我想将匹配的数据打印到另一个文件中。即在a1.txt中搜索到的第一个元素,在a2.txt中搜索的第二个元素,从而出现。目前你的帮助我能够将所有元素保存在一个文件中 – 2012-08-01 06:56:35

+0

这是否意味着你将拥有与匹配数量一样多的文件? – Hameed 2012-08-01 07:27:37

+0

非常感谢您的快速回复,.....是的,我将拥有与匹配数量一样多的文件。如果我在a.txt中有n个元素,那么将会搜索b.txt中的那些n元素,并且如果为所有n个元素找到匹配,那么它们将是n个文件。在我的情况下,这个数字可能在7-10个元素之间变化,因此7-10个文件。 – 2012-08-01 07:41:36

相关问题