Using awk or cut command to get CPU percentage

0

I am trying to execute a Linux command through a PHP script to get the CPU percentage for each core:

… with cut:

 $output = null;
 passthru("mpstat -P ALL | grep 0 | tr -s ' ' | cut -d ' ' -f 4", $output);
 echo "$output <br>";

… with awk:

$output = null;
passthru("mpstat -P ALL | grep 0 | tr -s ' ' | awk '{print $4}'", $output);
echo "$output <br>";

with the two statements the output is:

the name of my server 2.19 2.21 2.30 2.26 2.22 2.20 2.14 2.09 2.07 0

My server has an 8 core CPU and I want to use the output directly to Google charts, so I need just the CPU Percentage for 8 cores, without the server name.

Can help me with this issue?

Mohammed AL Jakry

Posted 2013-05-23T16:04:45.047

Reputation: 3

So what is your problem? Using echo(implode("\n", $output)[1]); does what you need? – Salem – 2013-05-23T16:20:50.537

thank you , but it still give me (the server name) before the numbers – Mohammed AL Jakry – 2013-05-23T16:27:40.440

If the server name always has the same length you can use `cut' to remove the first part. – Hennes – 2013-05-23T17:22:01.560

thanks but the server name is not always the same , i want to get just the numbers in awk or cut command ? – Mohammed AL Jakry – 2013-05-23T17:29:51.727

1@MohammedALJakry Can you use some paste service to provide the output of mpstat -P ALL? Executing exactly the same commands as you I don't get my host name on the output. I got the following (4 cores): 05/23/2013 %usr 6.71 8.05 7.45 5.87 5.48. – Salem – 2013-05-23T18:21:26.600

Linux 3.2.0-29-generic (h-cache52) 05/23/2013 x86_64 (8 CPU) 09:41:01 PM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %idle the statute for each core .... – Mohammed AL Jakry – 2013-05-23T19:36:16.357

Answers

1

I am echoing the string because my system's mpstat is different from what you show in your question but it should work if your output is what you have posted.

<?
$string="the name of my server 2.19 2.21 2.30 2.26 2.22 2.20 2.14 2.09 2.07 0";
$output=system("echo $string | perl -ne '/^.+?\s+([\d\. ]+)/; print \"$1\"'");
echo "$output <br>";
?>

The Perl script is just looking for the longest stretch of digits, decimal points and spaces ([\d\. ]+) and printing it, that should separate server names from the data with arbitrary server names. It will fail if your server's name ends with a number, something like foo bar 12. It will not treat the 12 as part of the server's name but as part of the data.

If your server names never contain spaces (which I assume they don't) you can use this gawk version if you prefer:

<?
$string="thenameofmyserver 2.19 2.21 2.30 2.26 2.22 2.20 2.14 2.09 2.07 0";
$output=system("echo $string | gawk '{for(i=2; i<=NF; i++){printf \"%s \",$(i)}}'");
echo "$output <br>";
?>

terdon

Posted 2013-05-23T16:04:45.047

Reputation: 45 216