Category Command-Line-Fu

Math using awk

Awk has built-in functionality to perform math with variables derived from a line. For example, let’s take a look at the output of df:

# df /
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda1 1942608 311772 1630836 16% /

To figure out the percentage used, simply take the available and divide that by the used. Using sed to trim off the header then piping the output to awk and adding a “%” string at the end of the calculation:

# df / | sed '1,1d' | awk '{print $3/$2*100"%"}'


For more information, please see The GNU Awk User’s Guide: Arithmetic Operators.

Read More