Bash – Formatting numbers using awk / print

awkbash

I found this very cool code to get upload/download speed:

awk '{ if (l1) {
        print "↓"($2-l1)/1024"kB/s ","↑"($10-l2)/1024"kB/s"
    } else {
        l1=$2; l2=$10;
    }
}' <(grep wlan0 /proc/net/dev) <(sleep 1; grep wlan0 /proc/net/dev)

However, it returns up to 4 decimals. I rather have no decimals whatsoever. I have previously been able to round numbers using bc or printf, but I seem to only be able to use print in awk. What is a good solution to this issue?

Best Answer

#!/bin/awk -f
{
     if (l1) {
             printf("↓ %.2f kB/s ↑ %.2f kB/s\n" \
               , ($2 - l1) / 1024, ($10 - l2) / 1024)
     } else {
             l1 = $2;
             l2 = $10;
     }
}

%.2f is a floating point number with two decimal places. Use %.0f or %i (integer) to display just the integral part.

Related Question