awk '$1 == prev1 {print $2 - prev2} {prev1=$1; prev2=$2}' file
Compute value from two consecutive rows, in case values in first column match
-
18-07-2023 - |
Question
I have a text file with two fields and I want to do subtractions between rows of the second column when there is a match in the first column.
In the example below, when (record 2 field 1) == (record 1 field 1) then I would compute (record 2 field 2) - (record 1 field 2) and print the result. When (record 2 field 1) != (record 1 field 1) I'd print nothing.
Then I would then increment the record number by 1 and repeat, i.e. compare record 3 with record 2.
Input
A001 100
A001 200
A001 201
B003 30
B007 700
C001 500
C001 700
Expected output
100
1
200
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow