我试图找到模式Pattern String
,一旦找到,我需要获取下一行模式,其中包含页码,我需要在下面的示例文本文件中提取页码2
Page: 2 of 5
。这是我的尝试:
my $filename="sample.txt";
$i=1;
open(FILE, "<$filename") or die "File couldn't be matched $filename\n";
@array = <FILE>;
foreach $line(@array){
chomp($line);
if ($array[$i]=~/(\s+)Pattern String(\s+)/) {
if ($array[$i]=~/(\s+)Page:(\s+)(.*) of (.*)/) {
$page = $3;
}
}
这是我的示例文本文件:
Pattern String
MCN: 349450A0 NCP Account ID: 999 600-0089 Page: 2 of 5
=============================================================================
Customer Name: PCS HEALTH SYSTEMS
Customer Number: 349450A0
答案 0 :(得分:1)
我认为这将解决问题(我假设示例文件将始终具有相同的格式)。我希望这会对你有所帮助,如果有效,请告诉我。
my $filename="sample.txt";
my $count = 0;
my $tgline = 0;
open(my $fh, "<", $filename) or die "Failed to open file: $!";
my @lines = <$fh>;
foreach (@lines) {
if ( $_ =~ /.*Pattern\sString.*/ ) {
$tgline = $count + 2;
if ( $lines[$tgline] =~ /.*Page\:\s(\d+)\sof\s(\d+)$/ ) {
print "Current page: " . $1 . "\n";
print "Total page #: " . $2 . "\n";
}
}
$count+=1;
}
答案 1 :(得分:1)
这个怎么样?那是你要的吗?匹配后如果下一行不为空,则显示该行。让我知道是否适合你。
# Perl:
my $filename="sample.txt";
my $match = undef;
my $line = "";
open(my $fh, "<", $filename) or die "Failed to open file: $!";
foreach (<$fh>) {
$line = $_;
if ( $line =~ /.*Pattern\sString.*/ ) {
$match = 1;
next;
}
if (($match == "1") && ($line !~ /^$/)){
print $line;
$match = undef;
}
}
答案 2 :(得分:0)
如果您的目标从输入文件中Pattern String
达到2
,我就不知道您为什么要匹配Page: 2 of 5
。这是一种获得此目的的方法:
use warnings;
use strict;
my $filename = "sample.txt";
open my $fh, "<","$filename" or die "Couldn't open $filename: $!";
while (my $line = <$fh>)
{
if($line =~ m/.*Page:\s(\d+)\sof\s(\d+)$/)
{
print "$1\n";
}
}
sample.txt的:
Pattern String
MCN: 349450A0 NCP Account ID: 999 600-0089 Page: 2 of 5
=============================================================================
Customer Name: PCS HEALTH SYSTEMS
Customer Number: 349450A0
输出:
2