如果行具有匹配的名称,则 awk 将两行相加

如果行具有匹配的名称,则 awk 将两行相加

我正在尝试获取一个类似这样的 csv 文件

customerID,firstname,lastname,charge
5efc522,Romo,goodrick,37.89
4a7f057,jeny,vel,38.39
5efc522,Romo,goodrick,39.00

并使其成为

firstname,lastname,chargetotal,customerID
ROMO,goodrick,76.89,5efc522
jeny,vel,38.39,4a7f057

到目前为止我知道我能做到

awk '{arr[$1]+=$4;}
END{
FOR (i in arr) {
print i, arr[i];}
'< file

任何帮助,将不胜感激

答案1

$ awk '
  BEGIN {OFS=FS=","} 
  NR==1 {print "firstname","lastname","chargetotal","customerID"} 
  FNR>1 {fname[$1]=$2; lname[$1]=$3; chargetotal[$1]+=$4} 
  END {for(i in chargetotal) print fname[i],lname[i],chargetotal[i],i}
' file.csv
firstname,lastname,chargetotal,customerID
jeny,vel,38.39,4a7f057
Romo,goodrick,76.89,5efc522

或者,使用磨坊主

$ mlr --csvlite --ofmt '%.2lf' stats1 -a sum -f charge -g customerID,firstname,lastname \
    then reorder -e -f customerID then rename charge_sum,chargetotal file.csv
firstname,lastname,chargetotal,customerID
Romo,goodrick,76.89,5efc522
jeny,vel,38.39,4a7f057

相关内容