Awk and printf in bash

I am trying to get a rounded amount of average load in the last 5 minutes. So here is my command:

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

Seems wrong as it always gives me 0.

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

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

So, is there something wrong with my first attempt?

Thank you and welcome!

UPDATE:

Just to get the average load in the last 5 minutes, here is the result of working 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 looks like

`$ uptime

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

That is why I take the 5th field.

+4
source share
5 answers

The 5th field, separated by commas, from the output of the uptime (at least on my system), so you keep getting zero. A 5-minute uptime is the second and last field, so this works:

 uptime | awk '{printf "%.0f\n",$(NF-1)}' 
+9
source

The simplest version (use the built-in awk printf - kudos Dennis Williamson ):

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

Original answer: Run it instead of xargs.

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

You can just do

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

Backticks is essentially command substitution, so regardless of the result of uptime | awk -F, '{print $5}' uptime | awk -F, '{print $5}' will be the argument to printf .

The problem with the first approach is that printf just does not accept arguments from stdin ; if it takes arguments from stdin then it would work fine. Also, no arguments to printf seem to mean "put zero for my arguments."

 $ echo hello | printf "%s" $ printf "%s" hello hello $ printf "%.0f" 0 
+1
source

I don’t think you can submit the printf input file to stdin. Try this version:

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

If you have / proc, you can use / proc / loadavg:

 LANG=C read _ uptime _ </proc/loadavg printf "%.0f\n" $uptime 

The code above uses only shell built-in commands. However, if you like, you can also use awk:

  awk '{printf "%.0f\n",$2}' /proc/loadavg 
+1
source

All Articles