Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk and printf in bash

Tags:

bash

printf

awk

I am trying to get the rounded number of the average load in the past 5 mins. So here goes my command:

 uptime | awk -F, '{print $5}'|printf "%.0f\n"

It seems incorrect as it always give me 0.

If I tried to use a variable as intermediate between awk and printf, then it is correct

 avgload=$(uptime | awk -F, '{print $5}')

 printf "%.0f\n" $avgload

So anything wrong with my first try?

Thanks and regards!

UPDATE:

Just for getting the average load in the past 5 mins, here is the output of uptime on my linux server (Kubuntu)

$ uptime
13:52:19 up 29 days, 18 min, 15 users, load average: 10.02, 10.04, 9.58

On my laptop (Ubuntu) it is similar

`$ uptime

13:53:58 up 3 days, 12:02, 8 users, load average: 0.29, 0.48, 0.60 `

That's why I take the 5th field.

like image 803
Tim Avatar asked Dec 05 '22 04:12

Tim


2 Answers

The 5th comma-separated field from the uptime output is non-existant (on my system at least), which is why you keep getting zero. The 5-minute uptime is the second-to-last field, so this works:

uptime | awk '{printf "%.0f\n",$(NF-1)}'  
like image 166
Paul Avatar answered Jan 27 '23 19:01

Paul


Simplest version (use built-in awk printf - kudos Dennis Williamson):

uptime |awk -F, '{printf "%0.f\n",$5}'

Original answer: Run it through xargs instead.

uptime |awk -F, '{print $5}' |xargs printf "%0.f\n"
like image 38
Will Bickford Avatar answered Jan 27 '23 20:01

Will Bickford