I'm trying to figure out how I can use AWK to subtract lines. For example, imagine the input file is:3020The output would be:10Now, as a test I am trying to calculate the Used memory column from:$ cat /proc/meminfoSo at the moment I have written this:$ grep -P 'MemTotal|MemFree' /proc/meminfo | \    -- Here comes the calculation using AWKI 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}'
How to subtract rows (lines) with AWK
linux;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- - | bc7513404DetailsThe above uses awk to select the column that contains the numbers we want to subtract.$ grep -P 'MemTotal|MemFree' /proc/meminfo | \    awk '{print $2}'7969084408432We 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-346660When we pass this to bc it performs the calculation.$ grep -P 'MemTotal|MemFree' /proc/meminfo | \    awk '{print $2}'| paste -sd- - | bc7513404