Issue with awk command between Linux and Solaris

Hi,

Here is the output using bash profile on Linux

 uptime
 04:59:14 up 16 days,  4:48,  2 users,  load average: 1.00, 1.00, 1.20

Here is the output using bash profile on Solaris

uptime
  4:00am  up 84 day(s), 22:21,  3 users,  load average: 0.09, 0.10, 0.12

Now, I m looking for a generic command to extract the average CPU Load which is the third column highlighted in BOLD RED

I tried the below command

uptime | awk -F" ,"  '{print $(NF-2)}' | cut -d ',' -f1

This works fine on Solaris but fails on Linux with the below error

awk: cmd. line:1: (FILENAME=- FNR=1) fatal: attempt to access field -1

Can you please help with a solution ?

Hello mohtashims,

Obviously it will come because you have set field separator as [[:space:]], (writing like [[:space:]] as with comma space is not coming into iCode tags here) and it couldn't find any field as NF-2 so thus giving an error because it is taking it as a single field.

Could you please try following and let me know if this helps you.

uptime | awk -F'[ ,]'  '{print $(NF-4)}'

If you need to know how fields are getting acquired then you could run following command too.

uptime | awk -F'[ ,]'  '{for(i=1;i<=NF;i++){print i,$i}}'

on a Solaris/SunOS system, change awk to /usr/xpg4/bin/awk , /usr/xpg6/bin/awk , or nawk .

Thanks,
R. Singh

1 Like

Hi.

Here is one solution that works in common:

OS, ker|rel, machine: Linux, 3.16.0-4-amd64, x86_64
Distribution        : Debian 8.7 (jessie) 

awk GNU Awk 4.1.1, API: 1.1 (GNU MPFR 3.1.2-p3, GNU MP 6.0.0)
$ uptime | awk -F, '{split($(NF-2),a,": ");print a[2]}'
0.67

and on

OS, ker|rel, machine: SunOS, 5.11, i86pc
Distribution        : Solaris 11.3 X86

awk - ( /usr/bin/awk, 2016-04-10 )
$ uptime | awk -F, '{split($(NF-2),a,": ");print a[2]}'
 0.02

Solaris awk is old, and can take only a single character -Fc :

       -Fc            Uses the character c as the field separator (FS) charac-
                      ter.  See the discussion of FS below.

excerpt from Solaris man awk, q.v.

There is a little matter of a leading space in Solaris output, easily fixed by setting to a variable and echoing without quotes, among other methods.

Both would also work with:

uptime | gawk -F, '{split($(NF-2),a,": ");print a[2]}'

OS, ker|rel, machine: SunOS, 5.11, i86pc
Distribution        : Solaris 11.3 X86
gawk GNU Awk 3.1.8

Best wishes ... cheers, drl

1 Like

Resolved:)

On linux, with the field separator set to ", " (instead non-existent " ,"), this is the result of post#1's awk script:

uptime | awk -F", "  '{print $(NF-2)}' | cut -d ',' -f1
 load average: 0