用于从文本文件中打印匹配行的Perl脚本

时间:2018-03-07 04:59:55

标签: regex perl

文字文件行:

2018-03-02 10:56:06,808 DEBUG [com.server.hdmi.xmlgenerator.XMLGenerator] XMLGenerator TLS ID size 142392_REQ_2018-03-02T09-53-18-991+10-00:3561
2018-03-02 10:56:02,074 DEBUG [com.server.hdmi.xmlgenerator.XMLGenerator] XMLGenerator TLS ID size 142401_REQ_2018-03-02T09-53-20-607+10-00:1444
2018-03-02 10:56:02,074 INFO  [com.server.hdmi.xmlgenerator.XMLGenerator] Exit createDOMTreefromXMLGenerator
2018-03-02 10:56:02,074 DEBUG [com.server.hdmi.xmlgenerator.XMLGenerator] generating file for TranID:142401:D:/InterfaceData/Address\142401_RESP_2018-03-02T10-55-35-035+10-00.xml

我的剧本:

my $LogDir = '\\\\server\\ddrive\support\purushoth\log';
    if(-e $LogDir)

    {                       
        opendir(DIR, $LogDir);
        while (defined(my $file = readdir (DIR)))   
        {           
            if ($file =~ m/server/i)
            {
            my $fullfilename = $LogDir."\\".$file;
            my @logFileLines = ();
            open (LOGFILE, "$fullfilename") or die "Could not open file";
                {
                    @logFileLines = <LOGFILE>;

                }
                close(LOGFILE);

                my $temp2 = 0;
                foreach my $line1 (@logFileLines)
                {
                    chomp($line1);      
                    if ( $line1 =~ (m!/^(\d{4}-\d{2}-\d{2}\s{1}\d{2}:\d{2}:\d{2})\s+.*XMLGenerator\s+TLS\s+ID\s+size\s+/.*\$!);
                    {
                    print "the line match in the server log:  $line1\n";
                    }
                 }            
            }
        }
    }

从日志文件中,我只想打印这样的匹配行。我尝试使用我的脚本,但它不起作用。

2018-03-02 10:56:06,808 DEBUG [com.server.hdmi.xmlgenerator.XMLGenerator] XMLGenerator TLS ID size 142392_REQ_2018-03-02T09-53-18-991+10-00:3561

请帮我阅读这些专栏并打印出来。而且我想分配这一行的最后一部分。

142392_REQ_2018-03-02T09-53-18-991+10-00:3561

1 个答案:

答案 0 :(得分:1)

如果问题出在正则表达式上,那么这里有正确工作的小样本:

#!/usr/bin/perl
my @lines = (
    '2018-03-02 10:56:06,808 DEBUG [com.server.hdmi.xmlgenerator.XMLGenerator] XMLGenerator TLS ID size 142392_REQ_2018-03-02T09-53-18-991+10-00:3561',
    '2018-03-02 10:56:02,074 DEBUG [com.server.hdmi.xmlgenerator.XMLGenerator] XMLGenerator TLS ID size 142401_REQ_2018-03-02T09-53-20-607+10-00:1444',
    '2018-03-02 10:56:02,074 INFO  [com.server.hdmi.xmlgenerator.XMLGenerator] Exit createDOMTreefromXMLGenerator',
    '2018-03-02 10:56:02,074 DEBUG [com.server.hdmi.xmlgenerator.XMLGenerator] generating file for TranID:142401:D:/InterfaceData/Address\142401_RESP_2018-03-02T10-55-35-035+10-00.xml'
);

foreach my $line (@lines) {
    if ($line =~ /^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).*XMLGenerator TLS ID size (.*)/) {
        print "Timestamp: $1, TLS ID: $2\n";
    } elsif ($line =~ /^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).*generating file for.*\\(.*)/) {
        print "Timestamp: $1, filename: $2\n";
    }
}