Awk

awk 按列分組並對多個值求和

  • July 13, 2022

我正在嘗試按“名稱”和總和值列“數量”和“價格”進行分組,範例數據如下:

names,fruits,qty,price
tom,banana,2,500
tom,banana,3,750
tom,apple,2,500
alex,banana,3,750
alex,melon,3,750
alex,melon,3,750
jess,banana,1,250
jess,banana,1,250
jess,banana,1,250
danny,melon,2,500
danny,apple,2,500
danny,apple,2,500

我已經嘗試使用這個命令:

awk -F, 'BEGIN{FS=OFS=","} 
           NR==1{print; next} 
           {
               q=$3; 
               $3="~";
               w=$4; 
               $4="~";
               a[$0]+=q;
               b[$0]+=w
           } 
      END  {
               for(k in a) 
               {
                   sub("~",a[k],k); 
                   sub("~",b[k],k);
                   print k
               }
           }' file

使用該命令,我在“價格”列中為空,我想要的輸出是這樣的:

names,fruits,qty,price
alex,banana,3,750
tom,banana,5,1250
alex,melon,6,1500
jess,banana,3,750
danny,apple,4,1000
danny,melon,2,500
tom,apple,2,500

在此先感謝您的幫助。

你可以做:

awk -F, -v OFS=, '
NR==1{ print; next }
{ key=($1 OFS $2) }
{ grpByQty[key]+=$3; grpByPrice[key]+=$4 }
END{ for(key in grpByQty) print key, grpByQty[key], grpByPrice[key] }' infile
BEGIN {
   FS = OFS = ","
}

NR == 1 {
   print $0
   next
}

NR > 1 {
   ori = price[$1 "," $2]
   if (ori == "") {
       price[$1 "," $2] = $3 "," $4
   } else {
       split(ori, a, ",")
       price[$1 "," $2] = a[1] + $3 "," a[2] + $4
   }
}

END {
   for (name in price) {
       print name, price[name]
   }
}

這個想法是儲存name與“,”連接並作為與“,”連接的fruit鍵和值。quantity``price

引用自:https://unix.stackexchange.com/questions/709696