代码之家  ›  专栏  ›  技术社区  ›  ant

从日志中提取特定模式

  •  1
  • ant  · 技术社区  · 14 年前

    我需要从如下的日志文件中提取请求:

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <vehicleRegistration>
    .... XML in between ....
    .... XML in between ....
    .... XML in between ....
    .... XML in between ....
    ... at nth line there is line like this <vehicle id="2312313"></vehicle>
    .... XML in between ....
    .... XML in between ....
    </vehicleRegistration>
    

    重要的问题是,车辆登记可以是5行,有时是17行,它是可变的。这就是我当前的grep失败的地方,我使用:

    grep -A 13 "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" vehicle.log
    

    另外一个问题是,有时一个请求可以发送2次或更多次,因为服务可能由于某种原因不可用,所以文件中可能有相同的多个请求。

    我还应该排除重复请求,通过比较第n行(不是最后一行)来知道请求是重复的方法。 <vehicle id="2312313"></vehicle> ,如果车辆ID重复,则为其副本。

    你怎么解决这个问题?建议,代码,伪代码,任何东西都欢迎。

    编辑:

    日志文件不是XML文件,它只是一个包含少量XML请求的文件,我无法将其解析为XML

    编辑二:

    我只提取了车辆注册部分,使用@eugene y一行命令 perl -nle 'm{<vehicleRegistration>} .. m{</vehicleRegistration>} and print' logfile ,如何消除重复项,那些具有相同车辆ID的节点,我只想保留这些节点的一个副本。

    4 回复  |  直到 14 年前
        1
  •  0
  •   Alex Reynolds    14 年前

    XPath

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    use XML::XPath;
    
    my $file = 'vehicleRegistration.xml';
    my $xp = XML::XPath->new(filename => $file);
    
    print "Vehicle id: ".$xp->find('//vehicle/@id')."\n";
    

        2
  •  2
  •   Eugene Yarmash    14 年前

    XML::Simple Data::Dumper

    vehicleRegistration

    open my $fh, '<', 'logfile' or die $!;     
    my $xml = ""; 
    
    while (<$fh>) {
        if ( m{<vehicleRegistration>} .. m{</vehicleRegistration>}) {
            $xml .= $_; 
        }   
    }
    

    perl -nle 'm{<vehicleRegistration>} .. m{</vehicleRegistration>} and print' logfile
    
        3
  •  1
  •   cryptochaos    14 年前

    #!/usr/bin/awk -f 
    
    /^<vehicleRegistration>/ { printit="true" } # set the print flag on
    printit ~ "true" { print }                  # if printflag set print
    /^</vehicleRegistration>{ printit="false" } # turn print flag off