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

868 Views Asked by At

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.

2

There are 2 best solutions below

2
On BEST ANSWER

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.

0
On

You don't need to use any external tool than top. Perl can do the rest:

#!/usr/bin/perl
use warnings;
use strict;

my $line;
open my $TOP, '-|', qw( top -b n 2 -d 0.01 ) or die $!;
while (<$TOP>) {
  $line = $_ if /Cpu\(s\)/;
}
my ($us, $ni, $wa) = (split ' ', $line)[1, 3, 5];
{   no warnings 'numeric';
    print $us + $ni + $wa, "\n";
}