我正在寻找一种方法来匹配单个字符串中的两个术语。例如,如果我需要匹配“foo”和“bar”以使字符串匹配并打印,并且字符串为“foo 121242Z AUTO 123456KT 8SM M10 / M09 SLP02369”,则不匹配。但如果字符串是“foo 121242Z AUTO 123456KT 8SM bar M10 / M09 SLP02369”,它将匹配,然后继续打印。这是我目前的代码,但我有点卡住了。谢谢!
use strict;
use warnings;
use File::Find;
use Cwd;
my @folder = ("/d2/aschwa/archive_project/METAR_data/");
open(OUT , '>', 'TEKGEZ_METARS.txt') or die "Could not open $!";
print OUT "Date (YYYYMMDD), Station, Day/Time, Obs Type, Wind/Gust (Kt), Vis (SM),
Sky, T/Td (C), Alt, Rmk\n";
print STDOUT "Finding METAR files\n";
my $criteria = sub {if(-e && /^/) {
open(my $file,$_) or die "Could not open $_ $!\n";
my $dir = getcwd;
my @dirs = split ('/', $dir);
while(<$file>) {
$_ =~ tr/\015//d;
print OUT $dirs[-1], ' ', $_ if /foo?.*bar/;
}
}
};
find($criteria, @folder);
close OUT;
print STDOUT "Done Finding Station METARS\n";
答案 0 :(得分:1)
为什么不简单:
perl -ne'print if /foo.*bar/'
如果您想要从某个目录处理更多文件,请使用find
find /d2/aschwa/archive_project/METAR_data/ -type f -exec perl -MFile::Spec -ne'BEGIN{$dir = (File::Spec->splitdir($ARGV[0]))[-2]} print $dir, ' ', $_ if /foo.*bar/' {} \; > TEKGEZ_METARS.txt
答案 1 :(得分:0)
#!/usr/bin/perl
use warnings;
use strict;
my $string1 = "foo 121242Z AUTO 123456KT 8SM M10/M09 SLP02369";
my $string2 = "foo 121242Z AUTO 123456KT 8SM bar M10/M09 SLP02369";
my @array = split(/\s+/, $string2);
my $count = 0;
foreach (@array){
$count++ if /foo/;
$count++ if /bar/;
}
print join(" ", @array), "\n" if $count == 2;
这将打印$string2
,但不打印$string1
答案 2 :(得分:0)
你可以通过两个字符串的正面预测来实现它:
print OUT $dirs[-1], ' ', $_ if m/(?=.*foo)(?=.*bar)/;