【问题标题】:How to parse and detect a block of lines from a log file in perl ?如何从 perl 的日志文件中解析和检测一行行?
【发布时间】:2013-06-18 19:15:15
【问题描述】:

我有一个文件看起来像这样

[
MsgName:XYZ
Status:Pass
]

[
MsgName:ABC
Status:Pass
]

[
MsgName:bbb
Status:Fail
Error
]

[
MsgName:ttt
Status:Pass
]

现在我想读取这个文件并创建 2 个日志文件 一个包含所有数据的常规日志和另一个包含只有错误数据的错误日志

所以在这种情况下,错误日志应该只显示

[

MsgName:bbb

Status:Fail

Error

]

并定期记录所有内容

谁能指导我如何做到这一点

我试过这种方式

while($line[i]=<FileHandle>
{

if($line[i]=~ /^s*\]/)
{
  print OUT "recd new msg-->:/n $line[i];
  next;
}
do

{
  print OUT "$line[i]";
  if($line[i]=~ /Error/)

{  ####this section i cannot figure out hw to frame it  get my desired output

   print "error found

   print ERROROUT .....

} until($line[i]=~ /^s\]

这里我使用 OUT 进行常规日志输出 和 ERROROUT 用于错误日志

【问题讨论】:

  • 只是添加我想要整个错误消息块,而不仅仅是错误行

标签: arrays perl parsing


【解决方案1】:

最简单的技巧是在您遍历文件时将您感兴趣的整个块存储在 fifo 中。

#!/usr/bin/perl 

use strict;
use warnings;

my @fifo=('') x 5; # Initialize an empty array with size = 5 (Message Block Size)
open(FILE,"log.txt");

while(<FILE>)
{
    push(@fifo,$_);       # Add element to the end of array making its size 6  
    shift @fifo;          # Remove first element reverting its size back to 5  
    if($fifo[3]=~/Error/) # Check if 4th line of block has error in it 
    {
        print @fifo;
    }
}
close(FILE)

【讨论】:

  • 除了存储和检查之外的任何其他方式......你有什么方法可以在遍历时同时检查
  • 如果这是您所要求的,此代码不会存储整个文件。它在遍历文件时只记住最后五行。所以本质上它是在遍历时进行检查。
猜你喜欢
  • 1970-01-01
  • 2012-01-09
  • 1970-01-01
  • 2015-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-03-23
  • 1970-01-01
相关资源
最近更新 更多