我想在另一个文件的文件里面写一些单词。我的代码能够在文件的最后一行grep这个单词而不是它之前的单词。我不知道为什么,希望可以在这里得到帮助。下面是我使用的perl脚本:
$month
我的file1.txt是这样的:
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);
我的file2.txt是这样的:
i am a dog
i am a cat
we are the fish
he is a boy
she is a girl
但是我的file3只能显示那些句子包含am但是没有,如果我放在第二行并且在第一行,那么我的file3只包含带有的句子。我不太清楚为什么我的代码只能grep我的file2中的最后一行。谢谢你的帮助。
答案 0 :(得分:2)
从文件中读取时,最终换行符是每行读取的一部分。您可以通过chomp:
从模式数组中删除换行符chomp( my @file2 = <FILE2> );
答案 1 :(得分:1)
您已经可以使用egrep:
执行此操作{{1}}
答案 2 :(得分:1)
此问题的根源是chomp
- 您没有删除换行符,因此匹配不起作用。
但除此之外,您的代码可能会遇到一些问题:
open (my $file1, '<', 'file1.txt' ) or die $!;
foreach my $line ( @things ) {
类型语法会更好。 所以你的代码实际上可以简化为:
#!/usr/bin/env perl
use strict;
use warnings;
open(my $data, '<',"file1.txt") or die $!;
open(my $search, '<', "file2.txt") or die $!;
open(my $output, '>', "file3.txt" ) or die $!;
chomp ( my @search_terms = <$search> );
#quotemeta is needed to avoid 'special' regex characters doing things.
my $search_regex = join "|", map { quotemeta }, @search_terms;
#note - '\b' denotes word boundary, which may not be what you want.
#means 'is' won't match 'fish'
#so get rid of them if that's not what you want.
$search_regex = qr/\b($search_regex)\b/;
print "Using: $search_regex\n";
select $output; #default print destination
while ( <$data> ) {
print if m/$search_regex/;
}
输出(在&#39; file3.txt&#39;中):
i am a dog
i am a cat
he is a boy
she is a girl
答案 3 :(得分:0)
请试试这个。
use strict;
use warnings;
use List::MoreUtils qw(uniq);
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";
my @file1=<FILE1>;
my @file2=<FILE2>;
my $j =0;
my $i =0;
foreach my $main_line(@file1){
chomp($main_line);
foreach my $line(@file2){
chomp($line);
if ($main_line =~ /$line/i) {
print FILE3 "$main_line\n";
}
}
}
close(FILE3);
感谢, praveenzx〜