-1

When I issue a command on the terminal uptime, it returns:

13:21:52 up 13:02, 3 users, load average: 1.10, 1.09, 0.96

Then, I want to print the load averages which are at field 8,9,10 by using:

uptime | awk '{print $8}' | tr -d ","

Then the result will be: 1.10

But, sometimes, when the pc is up for more than a day, it returns:

13:22:12 up 6 days, 19:50, 3 users, load average: 1.10, 1.09, 0.96

As you can see, the number of field columns is not fixed. I don't want to manually edit the field number I want to print. So, I thought of reading the line starting from the right side. With that, 0.96 will be the field 0, 1.09 will be field 1, and so on. I don't care about the values near the left side.

kvantour
  • 25,269
  • 4
  • 47
  • 72
Li Po
  • 43
  • 8
  • With `awk` you can use math to get the index number. So instead of `$8`, you can write `$(NF-2)` where `NF` is a variable which represents the number of fields in the current line/record. – kvantour Jan 07 '20 at 09:49

4 Answers4

2

You can do it with a single call to awk. The basic call would be:

uptime | awk '{ print $(NF - 2) }'

To get rid of the comma at the same time instead of creating another subshell with tr, you could do:

uptime | awk '{ gsub(/,/,""); print $(NF - 2) }'

Let me know if you have any further issues.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
1

In this way, you do not to worry about uptime issue.

cat /proc/loadavg|awk '{print $1,$2,$3}'
1

Another command with rev because rev is fun :

uptime | rev | cut -d , -f 3 | rev
Corentin Limier
  • 4,946
  • 1
  • 13
  • 24
0

If you just split by comma, the number of fields may vary, but if you split by colon first, and then by comma, the figure you are interested in is the first field in the last group:

uptime | cut -d : -f 5 | cut -d , -f 1
user1934428
  • 19,864
  • 7
  • 42
  • 87