0

My Command is below and its print Free CPU and Used CPU below format. I want to restrict awk output to 2 decimal place.

grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} {free=($5)*100/($2+$3+$4+$5)} END {print "Used Cpu:",usage "%"} {print "Free Cpu:",free "%"}'

Output :

Free Cpu: 98.9588%

Used Cpu: 1.04125%

Desired output :

Free Cpu: 98.95%

Used Cpu: 1.04%
3
  • 2
    use printf: printf "Used Cpu: %.2f%%\n", usage – glenn jackman Jan 26 '19 at 16:59
  • 1
    Note, your END block only prints "Used Cpu" -- the block that prints "Free Cpu" is not in the END block, and wil therefore print for each line of input. – glenn jackman Jan 26 '19 at 17:01
  • Hi Glenn, I tried your suggestion and its work for me. Edited command is below: grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} {free=($5)*100/($2+$3+$4+$5)} {printf "Used Cpu: %.2f%%\n", usage} {printf "Free Cpu: %.2f%%\n", free}' Used Cpu: 2.18% Free Cpu: 97.82% Thank you so much. – Sandeep Singh Jan 27 '19 at 16:07
1

An alternative way is to define an output format OFMT="%5.2f%%" to format all numeric output:

$ awk -v OFMT="%5.2f%%" '
         $1 == "cpu" {
                       print( "Used Cpu: ", 100*($2+$4)/($2+$4+$5) )
                       print( "Free Cpu: ", 100*$5/($2+$3+$4+$5) )
                     }
         ' /proc/stat


Used Cpu:   9.52%
Free Cpu:  90.48%
2
  • Hi Isaac, Thanks for reply. Can you please explain what is OFMT here. Thanks Sandeep – Sandeep Singh Jan 27 '19 at 15:59
  • Thanks Isaac its working with print in awk. – Sandeep Singh Jan 27 '19 at 16:11
3

A bit of code review:

  • awk can do what grep does, so you don't need the pipeline
  • add newlines to the awk code for reability

For example:

awk '$1 == "cpu" {
  printf "Used Cpu: %5.2f%%\n", 100*($2+$4)/($2+$4+$5)
  printf "Free Cpu: %5.2f%%\n", 100*$5/($2+$3+$4+$5)
}' /proc/stat

which outputs the nicely aligned

Used Cpu:  5.34%
Free Cpu: 94.63%
2
  • Is it possible to print output like below. Used Cpu;Free Cpu 5.34%;94.63% – Sandeep Singh Jan 27 '19 at 17:34
  • Of course. Just modify the print statements. – glenn jackman Jan 27 '19 at 17:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.