2017-06-14 71 views
-2

示例日志内的日志文件中的特定的字符串,如何读取从perl脚本

2016年3月29日10点57分28秒642 UTC [31871] INFO节点信息: {“数据中心” :“TEST-DC”,“infraType”:“saas”,“service”:“fusion”, “extraInfo”:{“systemType”:“secondary-ha1”,“tenantType”:“sales”, “tenantName “: “sale1”}

我想读 “tenantName”: “sale1” 和最后一个字符串我需要的是 “sale1”

试着用AWK和削减Perl脚本内,但并没有制定出任何建议和/或暗示将很可观

我得到的答案的解决方案,从@Sobrique

使用的模块JSON &名单:: MoreUtils

find(\&Count, $logDir); 

my @uniqtotal = uniq @totCount; 
$totalcount = @uniqtotal; 

sub Count { 
    if($File::Find::name =~m!$logDir/(.*?)/$pattern! and -f $File::Find::name) { 
    my $jsonLine = `grep 'tenantName' $File::Find::name`; 
    if ($jsonLine ne "") { 
     $jsonLine =~ m/(\{.*\})/ ; 
     my $json_text = $1; 
     my $json = decode_json ($json_text); 
     push @totCount, $json -> {extraInfo} -> {tenantName}; 
    } 
    } 
} 
+1

建议:请出示你尝试过什么。 (编辑问题以添加您的代码。) – zdim

回答

1

不管awk和sed在perl脚本里面。

这是JSON,所以最好解析为JSON。

#!/usr/bin/env perl 

use strict; 
use warnings; 

use JSON; 

while (<>) { 
    my ($json_text) = m/(\{.*\})/; 
    my $json = decode_json ($json_text); 
    print $json -> {extraInfo} -> {tenantName}; 
} 

或者简化到一个衬垫,因为这是hoopy事做:

perl -MJSON -ne 'print decode_json (/(\{.*\})/ && $1)->{extraInfo}{tenantName}' 
+0

谢谢你的建议 – akbharath

0

sed

sed -r 's/.*"tenantName": "([^"]+).*/\1/g' inputfile 
sale1 

Exaplanation: grep-o标志将只打印字符串的匹配部分而不是整行。 -P标志将启用perl正则表达式为grep\K:手段忘记了左边的所有内容。

+1

谢谢@PS。它工作完美,我的坏不考虑grep或sed较早 – akbharath