How to subtract rows (lines) with AWK

You can also do this using awk, paste, and bc. I find this approach easier to remember, the syntax of awk always requires me to look things up to confirm.

NOTE: This approach has the advantage of being able to contend with multiple lines of output, subtracting the 2nd, 3rd, 4th, etc. numbers from the 1st.

$ grep -P 'MemTotal|MemFree' /proc/meminfo | \
    awk '{print $2}' | paste -sd- - | bc
7513404

Details

The above uses awk to select the column that contains the numbers we want to subtract.

$ grep -P 'MemTotal|MemFree' /proc/meminfo | \
    awk '{print $2}'
7969084
408432

We then use paste to combine these 2 values values and add the minus sign in between them.

$ grep -P 'MemTotal|MemFree' /proc/meminfo | \
    awk '{print $2}'| paste -sd- -
7969084-346660

When we pass this to bc it performs the calculation.

$ grep -P 'MemTotal|MemFree' /proc/meminfo | \
    awk '{print $2}'| paste -sd- - | bc
7513404

The purely awk solution, no redundant cat or grep commands:

awk '/MemTotal/ {TOT=$2} /MemFree/ {FREE=$2} END {printf("%d kB Used\n", TOT-FREE)}' /proc/meminfo

I see awk_FTW beat me to it but I though formatting the output could be nice.


Try this:

grep -P 'MemTotal|MemFree' /proc/meminfo | \
awk 'NR==1{s=$2;next}{s-=$2}END{print s}'

Tags:

Linux

Awk