macosbashawksargeektool

use awk to convert bytes to Kbytes in network output


Attempting to use geektool to show average Kbytes in and out on my mac

Thinking to use sar awk and grep for this but sar outputs in bytes and I want Kbytes

sar -n DEV 1 1 | grep -i 'average.*en0' (obviously would use more data but 1 1 is fast)

Sample output

Average:   en0            1            68           2           132

sar -n DEV 1 1 | grep -i 'average.*en0' | awk '{print $4, $6}'

Sample output

68 132

How would I use awk to convert this byte/ps output to Kbytes/ps?

Answer:

sar -n DEV 1 1 | grep -i 'average.*en0'| awk '{printf "i: %.2f Kbps\no: %.2f Kbps\n", $4 / 1024, $6 / 1024 }'

This replaces doing it with netstat with 11 lines of code, which I think was less accurate and alot more code


Solution

  • awk '{printf "%.2f %.2f\n", $4 / 1024, $6 / 1024 }'
    

    will print kilobytes with two decimal points.

    $ line="Average:   en0            1            68           2           132"
    $ echo "$line" | awk '{printf "%.2f %.2f\n", $4 / 1024, $6 / 1024 }'
    0.07 0.13