【发布时间】:2017-03-29 07:15:47
【问题描述】:
我想从另一个文件中 grep 文件中的一些单词。我的代码能够 grep 文件最后一行的单词,但不能grep 前面的单词。我不知道为什么,希望能在这里得到帮助。下面是我使用的 perl 脚本:
open(FILE1,"file1.txt") or die "Error, File1 could not open\n";
open(FILE2,"file2.txt") or die "Error, File2 could not open\n";
open(FILE3, ">file3.txt") or die "Error, File3 could not open\n";
use strict;
use warnings;
use List::MoreUtils qw(uniq);
my @file1=<FILE1>;
my @file2=<FILE2>;
my $j =0;
my $i =0;
my $zone =0;
for ($j=0; $j<=$#file2; $j++){
$zone = $file2[$j];
unless ( $zone =~ m/#(.*?)/ ) {
print "$zone";
my @fid = grep /$zone/ , @file1;
@fid = uniq(@fid);
s{^\s+|\s+$}{}g foreach @fid; #cancel leading space
for ($i=0; $i<=$#fid; $i++){
print FILE3 "$fid[$i]\n";
}
#@fid=();
}
}
close(FILE3);
我的 file1.txt 是这样的:
i am a dog
i am a cat
we are the fish
he is a boy
she is a girl
我的file2.txt是这样的:
is
am
但是我的file3只能显示那些包含am但不是is的句子,如果我把is放在第二行,am放在第一行,那么我的file3只包含is的句子。我不太确定为什么我的代码只能 grep 文件 2 中的最后一行。感谢您的帮助。
【问题讨论】: