简体   繁体   中英

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

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

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
$ awk 'BEGIN   {FS=OFS="|"} 
       NR==FNR {a[$1]=$2;next} 
       $1 in a {v=a[$1]; print $1,$4,v,(v>$4?$4*v:$4-v),$3}' b a

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

Explanation

set the delimiters for parsing and printing the fields

while scanning the first file (file b) where the linenumber and file line number are equal, fill up the lookup array with key value pairs.

while scanning the second file (now the third statement in the script), if the key in in the array, print the fields in desired order and with the described computation.

To not to rewrite a[$1] multiple times assign it to variable v (for value).

Using Perl one-liner

> cat filea
Jimmy|03-OCT-18|BST100114261|20000
Dedi|03-OCT-18|BST100904288|10000
Jimmy|03-OCT-18|BST100114262|120000
> cat fileb
Anton|9800
Jimmy|90000
> perl -F"\|" -lane ' BEGIN { %kvp=map{chomp;split(/\|/)} qx(cat fileb)} { chomp;print "$F[0]|$F[3]|$kvp{$F[0]}|",$F[3]<$kvp{$F[0]}?$F[3]*$kvp{$F[0]}:$F[3]-$kvp{$F[0]},"|$F[2]" if $kvp{$F[0]} } ' filea
Jimmy|20000|90000|1800000000|BST100114261
Jimmy|120000|90000|30000|BST100114262
> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM