0

Below is the output of uptime from Solaris where I am extracting the third last column:

uptime
8:30pm  up 23 day(s), 17:46,  5 users,  load average: **2.79**, 1.79, 1.53

I always need to get the third last column highlighted in bold above i.e. 2.79

echo '8:30pm  up 23 day(s), 17:46,  5 users,  load average: 2.79, 1.79, 1.53' | awk '{ print substr($10, 1, length($10)-1) }'

Output:
2.79

But at times it fails when uptime output has 18 hr(s) instead of 17:46 as seen below:

echo '8:44pm  up 23 day(s), 18 hr(s),  5 users,  load average: 1.08, 1.12, 1.22' | awk '{ print substr($10, 1, length($10)-1) }'

Output:
average

A simple solution could be searching for the columns from the last column minus 3 i.e 3rd column from last as the last three columns are always numerical and don't change. However, I m not sure how-to.

Can you please suggest ?

1

Read man cut and do something like:

uptime  | cut -d, -f4 | cut -d: -f2
0

You may try this out.

awk -F ':' '{ print 0+substr($NF, 1, -1+index($NF,","))}'
0

To always get the third last column all you need to do is to count backwards from the end of the line instead of forwards from the front of it:

awk '{print $(NF-2)+0}'

For example:

$ echo '8:30pm  up 23 day(s), 17:46,  5 users,  load average: 2.79, 1.79, 1.53' | awk '{print $(NF-2)+0}'
2.79

$ echo '8:44pm  up 23 day(s), 18 hr(s),  5 users,  load average: 1.08, 1.12, 1.22' | awk '{print $(NF-2)+0}'
1.08

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.