Chinaunix

标题: 同类列相加输出 [打印本页]

作者: xjxh829    时间: 2014-08-04 23:10
标题: 同类列相加输出
一个文件如下,
AAA,3,2014
BBB,1,2013
AAA,2,2012
AAA,1,2014

输出结果为
AAA,4,2014
BBB,1,2013
AAA,2,2012

用perl作hash处理就比较简单。但想用awk和shell处理,涉及数组,具体怎么实现,没有想好方法。
作者: yestreenstars    时间: 2014-08-04 23:43
  1. $ awk -F'[,,]' '{a[$1","$3]+=$2}END{for(i in a){sub(/,/,","a[i]",",i);print i}}' i
  2. BBB,1,2013
  3. AAA,2,2012
  4. AAA,4,2014
复制代码

作者: Kasiotao    时间: 2014-08-04 23:58
回复 1# xjxh829
  1. awk -F\, '{a[$1","$3]+=$2}END{for(i in a){sub(/,/,","a[i]",",i);print i}}' testfile
复制代码
如果输出没有顺序要求的话;这个可以
  1. AAA,3,2014
  2. BBB,1,2013
  3. AAA,2,2012
  4. AAA,1,2014
  5. AAA,1,2014
  6. CCC,2,2014
  7. CCC,4,2014
  8. BBB,2,2013
复制代码
结果
  1. BBB,3,2013
  2. CCC,6,2014
  3. AAA,2,2012
  4. AAA,5,2014
复制代码

作者: Kasiotao    时间: 2014-08-05 00:00
回复 2# yestreenstars
。。。。神似阿,星辰大大


   
作者: yestreenstars    时间: 2014-08-05 08:53
回复 4# Kasiotao

不错不错,加油!
   
作者: xjxh829    时间: 2014-08-06 09:48
没有用shell处理的方法吗?指教下
作者: li0924    时间: 2014-08-06 15:18
回复 3# Kasiotao
考虑顺序
  1. awk -F"[,,]" '{if(! a[$1$3]++){b[++n]=$1;c[++m]=$3}d[$1$3]+=$2}END{for(i=1;i<=n;i++)print b[i]","d[b[i]c[i]]","c[i]}' file
复制代码

作者: yestreenstars    时间: 2014-08-06 15:37
回复 6# xjxh829

shell包含了awk
   
作者: lvyuancyx    时间: 2014-08-06 16:25
回复 4# Kasiotao


考虑的非常周全,把半角,都替换了.




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2