# AWK, Compare of two files then compare the other field for the match one and do arithmetic

2979 views
0

File A

``````Jimmy|03-OCT-18|BST100114261|20000
Dedi|03-OCT-18|BST100904288|10000
Jimmy|03-OCT-18|BST100114262|120000
``````

File B

``````Anton|9800
Jimmy|90000
``````

Output

``````Jimmy|20000|90000|1800000000|BST100114261
Jimmy|120000|90000|30000|BST100114262
``````

Logic:

1. Find the same Jimmy
2. Compare amount between File A (column 4) and File B (column 2), if File A (column 4) less than File B (column 2) then multiple File A (column 4) and File B (column 2). If it is less, then deduct File A (column 4) and File B (column 2)

Note :

• 90000 > 20000 then 20000 * 90000 = 1800000000

• 90000 < 120000 then 120000 - 90000 = 30000

1. Display output as above

7

Could you please try following once.

``````awk '
BEGIN{
FS=OFS="|"
}
FNR==NR{
a[\$1]=\$2
next
}
(\$1 in a){
if(\$4<a[\$1]){
val=\$4*a[\$1]
if(val<a[\$1]){
val_new=\$4-a[\$1]
}
}
else{
val=\$4-a[\$1]
}
print \$1,\$4,a[\$1],val_new?val_new:val,\$3
val_new=val=""
}
' Input_fileb   Input_filea
``````

Output will be as follows.(Only tested with provided samples in case any conditions then do let us know please)

``````Jimmy|20000|90000|1800000000|BST100114261
Jimmy|120000|90000|30000|BST100114262
``````

posted this