perlawkqx

Unable to get output from awk in a variable using Perl Script.


I am a newbie in Perl Scripting. I am working on code in which I have to get CPU utilization. I am trying to run a command and then get the output in a variable. But when I try to print the variable I get nothing on the scree.

Command works fine in the terminal and gives me an output. ( I am using Eclipse ).

my $CPUusageOP;
$CPUusageOP = qx(top -b n 2 -d 0.01 | grep 'Cpu(s)' | tail -n 1 | gawk '{print $2+$4+$6}'); 
print "O/P of top command ", $CPUusageOP;

Output I get is :

    O/P of top command

Expected output :

    O/P of top command 31.4

Thanks.


Solution

  • qx() will interpolate $2 etc in your gawk, which you would have known if you had used warnings

    use strict;
    use warnings;
    

    So you need to escape them:

    ... gawk '{print \$2+\$4+\$6}'); 
    

    Also, of course, this is a silly thing to do in Perl. You can do all of that, except top (which may still be available in some module). E.g.:

    my @lines = grep { /\QCpu(s)/ } qx(top -b n 2 -d 0.01);
    my $CPUusageOP = $lines[-1];
    $CPUusageOP = ( split ' ', $CPUusageOP )[1,3,5];
    

    I cannot remember if awk starts the field designations with $1 or $0, but tweak it as you like.