in reply to Re^2: How to fetch the value of unix command result
in thread How to fetch the value of unix command result

Hi Experts,

Below is my code, unix command executes on zip file and displays the count of field 3, based on the value in field 3, i have 10 records in zip file, the field 3 contains word CHECK and KCEHC, the command which is used counts the number of CHECK and KCEHC

my $result1 = `gunzip -c $file|cut -f3 -d'|'|sort|uniq -c`;

The input zip file contains, the 11 records

ABC|123|CHECK|1| DEF|456|CHECK|1| GHI|789|CHECK|1| JKL|101|CHECK|1| ABC|123|CHECK|1| DEF|456|CHECK|1| GHI|789|CHECK|1| JKL|101|KCEHC|1| ABC|123|KCEHC|1| DEF|456|KCEHC|1| GHI|789|KCEHC|1|

gives me this error message / faulty output:

2 4 CHECK 6 KCEHC

I need to store the values 4 in $c and 6 in $c2, could you please suggest how can we do that

I also tired the below one....

my $r = `gunzip -c $file|cut -f3 -d'|'|sort|uniq -c`; my $c1 = substr( $r, 16,-2); my $c2 = substr( $, 9,-9);

This gives me the output as...

<code> $c1 = 4 $c1 = 6 <code>

I have a question to experts, was this correct method

Replies are listed 'Best First'.
Re^4: How to fetch the value of unix command result
by rjt (Curate) on Jun 30, 2013 at 12:45 UTC

    I also tired the below one....

    my $r = `gunzip -c $file|cut -f3 -d'|'|sort|uniq -c`; my $c1 = substr( $r, 16,-2); my $c2 = substr( $, 9,-9);

    This gives me the output as...
    <code> $c1 = 4 $c1 = 6 <code>

    I have a question to experts, was this correct method

    In a word, no. It might (and I emphasize, might) work for your current input. What happens, though, when:

    • You need to add, remove, or change one of the keywords you are interested in?
    • Someone gives you a data file containing an entry like this: GHI|789|DHECK|1|
    • Pretty much anything changes with the format of the output from that pipeline?
    • Someone asks you, "hey, why doesn't this work on Windows?"
    • You forget whether $c1 has the value for CHECK...or was it $c2?
    • ...

    Maybe you'll be ridiculously lucky and not ever encounter any of the above scenarios. But I guarantee, if you continue writing code that takes inherently variable width text input and parses it with fixed offsets, it will blow up horribly at some point.

      Hi Expert,

      I have used your code and tested and i found the below output

      code

      #!/usr/bin/env perl use warnings; use strict; use IO::Zlib; my $fh = IO::Zlib->new('test.txt.gz', 'rb') or die "Zlib failed: $!"; my %count; $count{$_}++ for map { (split /\|/)[2] } <$fh>; printf "%-10s %4d\n", $_, $count{$_} for sort keys %count;

      The output which i got

      <ocde> CHECK 7 KCEHC 4 </code>

      Can i store them separately in $c and $c1 ? how can i print them individualy, how can i assign 4 to $c1 and 7 to $c1, please explain

        how can i assign 4 to $c1 and 7 to $c1

        Are you sure you mean that, or should one of those $c1s be $c ?

        poj