从文件中提取Perl模式
我有一个文本文件,如:从文件中提取Perl模式,perl,Perl,我有一个文本文件,如: Name : first File name : first_1 Year : 12 etc etc etc T1 : this is t1 T2 : this is t2 T3 : this is t3 Conclusion : Success Name : first File name : first_2 Year : 13 etc etc etc T1 : this is t1 T2 : thi
Name : first
File name : first_1
Year : 12
etc
etc
etc
T1 : this is t1
T2 : this is t2
T3 : this is t3
Conclusion : Success
Name : first
File name : first_2
Year : 13
etc
etc
etc
T1 : this is t1
T2 : this is t2
T3 : this is t3
Conclusion : Success
Name : second
File name : second_1
Year : 12
etc
etc
etc
T1 : this is t1
T2 : this is t2
T3 : this is t3
Conclusion : Failure
Name : first
File name : first_3
Year : 12
etc
etc
etc
T1 : this is t1
T2 : this is t2
T3 : this is t3
Conclusion : Success
等等
我需要一个perl脚本,它提供以下输出:
Naming File_name Year Conclusion Reason
first first_1 12 Success this is t1, this is t2, this is t3
first first_2 13 Success this is t1, this is t2, this is t3
second second_1 12 Failure this is t1, this is t2, this is t3
first first_3 12 Success this is t1, this is t2, this is t3
您没有指定您遇到的问题。将流拆分为记录?这将实现以下目的:
my @buf;
while (<>) {
if (@buf && /^Name :/) {
process_record(@buf);
@buf = ();
}
push @buf, $_;
}
process_record(@buf) if @buf;
my@buf;
而(){
如果(@buf&&/^Name:/){
过程记录(@buf);
@buf=();
}
按@buf,$\ux;
}
如果@buf,则处理记录(@buf);
以下内容满足您的需要。它从STDIN读取要解析的文件。可以是任何其他行数组
#!/usr/bin/perl
use strict;
my $Naming = "";
my $File_name = "";
my $Year = "";
my @Reason = ();
my $Conclusion = "";
print "Naming\tFile_name\tYear\tConclusion\tReason\n";
while (my $line = <STDIN>) {
$line =~ /Conclusion : (\w+)/ and do {
$Conclusion = $1;
print "$Naming\t$File_name\t$Year\t$Conclusion\t" . join(", ",@Reason) . "\n";
$Naming = "";
$File_name = "";
$Year = "";
@Reason = ();
$Conclusion = "";
};
$line =~ /Name : (.*)/ and $Naming = $1;
$line =~ /File name : (.*)/ and $File_name = $1;
$line =~ /Year : (\d+)/ and $Year = $1;
$line =~ /T\d : (.*)/ and push(@Reason,$1);
}
#/usr/bin/perl
严格使用;
我的$Naming=“”;
我的$File_name=“”;
我的$Year=“”;
我的@Reason=();
我的$结论=”;
打印“命名\t文件\u名称\t耳朵\t结论\t叛逆\n”;
while(我的$line=){
$line=~/结论:(\w+)/和do{
$结论=$1;
打印“$Naming\t$File\u name\t$Year\t$Conclusion\t”。加入(“,”,@Reason)。“\n”;
$Naming=“”;
$File_name=“”;
$Year=“”;
@原因=();
$结论=”;
};
$line=~/Name:(.*)和$Naming=$1;
$line=~/文件名:(.*)和$File\u name=$1;
$line=~/年:(\d+)/和$Year=$1;
$line=~/T\d:(.*)和push(@Reason,$1);
}
所以这不是一个为我编写代码的网站。您必须自己尝试,当您被困在某个地方时,请在此处陈述您的问题,然后您将获得帮助。@dgw为此感到抱歉,我尝试了以下方法:@dgw为此感到抱歉,我尝试了以下方法:使用严格的;使用警告;我的$readLine;我的$string;打开(TEST_READ,“READ.txt”)| | die“无法打开READ.txt,$!”;打开(TEST_WRITE,“>WRITE.txt”)| | die“无法创建WRITE.txt,$!”;而($readLine=){if($readLine=~m/Name:(.*))或$readLine=~m/文件名:(.*)/或$readLine=~m/年:(.*)/或$readLine=~m/结论:(.*)/{$string=~s/$string=~s/\s+$/;打印测试写$string;打印测试写“\n”}关闭测试读;闭式测试写入@沙吉:没人能看得到。请编辑您的问题并将代码放在那里。确保缩进4个空格,将其标记为代码标记。