-2

sample log,

2016-03-29 10:57:28 UTC 642 [31871] INFO node information: {"datacenter": "TEST-DC", "infraType": "saas", "service": "fusion", "extraInfo": {"systemType": "secondary-ha1", "tenantType": "sales", "tenantName": "sale1"}

I want to read "tenantName": "sale1" and the final string I need is "sale1"

tried with awk and cut inside the Perl script but didn't work out Any suggestions and/or hints will be appreciable

I got the solution with the answer from @Sobrique

used the modules JSON & List::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};
    }
   }
}
akbharath
  • 3
  • 5

2 Answers2

1

Don't awk and sed inside a perl script anyway.

This is JSON, so best parsed as 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};
}

Or simplifying down to one liners, because that's the hoopy thing to be doing:

perl -MJSON -ne 'print decode_json (/(\{.*\})/ && $1)->{extraInfo}{tenantName}'
Sobrique
  • 52,974
  • 7
  • 60
  • 101
0
grep -oP 'tenantName": "\K[^"]+' inputfile
sale1

or sed:

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

Exaplanation: grep : -o flag will print only the matching part of the string not the whole line. -P flag will enable the perl regex for grep. \K: Means forget everything on the left of it.

P....
  • 17,421
  • 2
  • 32
  • 52