I'm trying to figure out how I can use AWK to subtract lines. For example, imagine the input file is:
30
20
The output would be:
10
Now, as a test I am trying to calculate the "Used" memory column from:
$ cat /proc/meminfo
So at the moment I have written this:
$ grep -P 'MemTotal|MemFree' /proc/meminfo | \
-- Here comes the calculation using AWK
I have tried the following:
$ grep -P 'MemTotal|MemFree' /proc/meminfo | \
awk '{print $2}' | awk '{$0-s}{s=$0} END {print s}'
But this just gives me the last row of data.
I've found a working solution, but I doubt it's the most optimal one. All my coding experience tells me that hard coding the amount of rows is terrible :P
$ grep -P 'MemTotal|MemFree' /proc/meminfo | \
awk '{print $2}' | awk 'NR == 1{s=$0} NR == 2 {s=s-$0} END {print s}'
line1_$2 - line2_$2 - lineN-$2
? Do you only want to subtract the first two consecutive rows? – terdon♦ Mar 2 '14 at 16:55