eh2deni
eh2deni

Reputation: 69

Calculations in AWK

I need to perform calculations in awk. For each array[$1,$2] i need to check $3. If it is "5310" the value in $4 is positiv, else the value is negativ. In the end I need to substract all negativ values from the positiv values per array[$1,$2]

input

K019001^ABC^531^12   
K019001^ABC^601^12  
K019002^ABC^531^100  
K019002^ABC^601^40  
K019003^ABC^531^50  
K019003^ABC^601^30  
K019003^ABC^601^40  
K019004^ABC^531^10

desired output

K019001^ABC^0  
K019002^ABC^60  
K019003^ABC^-20  
K019004^ABC^10

Upvotes: 0

Views: 357

Answers (1)

anubhava
anubhava

Reputation: 785146

Use this awk:

awk 'BEGIN {FS=OFS=SUBSEP="^"} {a[$1,$2] += $4 * ($3==531 ? 1 : -1)} 

END {for (i in a) print i, a[i]}' file

K019001^ABC^0
K019004^ABC^10
K019002^ABC^60
K019003^ABC^-20

UPDATE:: To get correct ordering:

awk 'BEGIN{FS=OFS="^"} {k=$1 FS $2; if (!a[k]) b[c++]=k} $3==531{a[k]+=$4; next} {a[k]-=$4}
        END {for (i=0; i<length(b); i++) print b[i], a[b[i]]}' file

K019001^ABC^0
K019002^ABC^60
K019003^ABC^-20
K019004^ABC^10

Upvotes: 4

Related Questions