从CSV文件awk的条件求和 [英] Awk conditional sum from a CSV file

查看:414
本文介绍了从CSV文件awk的条件求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我想提取某些资料的CSV文件:在一个柱每个不同的值,我想计算另一列的相应值的总和。最后,我可能会做它在Python,但我相信有可能是用一个简单的解决方案 AWK

这可能是CSV文件:

  2 1:2010年1月喇嘛:喇嘛1.6
2:2010年1月喇嘛:喇嘛1.1
2:2010年1月喇嘛:喇嘛3.4
2 3:2010年1月喇嘛:喇嘛-1.3
2 3:2010年1月喇嘛:喇嘛6.0
2 3:2010年1月喇嘛:喇嘛1.1
2 4:2010年1月喇嘛:喇嘛-1.0
2 5:2010年1月喇嘛:喇嘛10.9

我想获得:

  1 1.6
2 4.5
3 5.8
4 -1.0
5 10.9


现在,我只能提取:

一)第一柱的值:

 的awk -F'''{$打印(2)}'MyFile.csv | awk的-F:'{$打印(1)}

然后得到:

  1
2
2
3
3
3
4

b)和值等于说, 1.1 在最后一栏:

的awk -F'''{$打印(NF)}'MyFile.csv | awk的'$ 1 == 1.1

然后得到:

  1.1
1.1

我不能够同时提取我感兴趣的列,这可以帮助我到底。下面是一个示例输出,可以缓解资金的计算(我不知道):

  1 1.6
2 1.1
2 3.4
3 -1.3
3 6.0
3 1.1
4 -1.0
5 10.9

编辑:感谢Elenaher,我们可以说在输入高于文件


解决方案

  $ awk的-F[:\\ t] +'{a [$ 2] + = $ NF} END {为(我的)打印I,A [I]}'文件
4-1
5 10.9
1 1.6
2 4.5
3 5.8

I have a CSV file from which I would like to extract some pieces of information: for each distinct value in one colum, I would like to compute the sum of the corresponding values in another column. Eventually, I may do it in Python, but I believe there could be a simple solution using awk.

This could be the CSV file:

2    1:2010-1-bla:bla    1.6
2    2:2010-1-bla:bla   1.1
2    2:2010-1-bla:bla    3.4
2    3:2010-1-bla:bla    -1.3
2    3:2010-1-bla:bla    6.0
2    3:2010-1-bla:bla    1.1
2    4:2010-1-bla:bla    -1.0
2    5:2010-1-bla:bla    10.9

I would like to get:

1    1.6
2    4.5
3    5.8
4    -1.0
5    10.9


For now, I can only extract:

a) the values of the first colum:

awk -F ' ' '{print $(2)}' MyFile.csv | awk -F ':' '{print $(1)}'

and then get:

1
2
2
3
3
3
4
5

b) and the values equal to, say, 1.1 in the last column with:

awk -F ' ' '{print $(NF)}' MyFile.csv | awk '$1 == 1.1'

and then get:

1.1
1.1

I am not able to simultaneously extract the columns I am interested in, which may help me in the end. Here is a sample output which may ease the computation of the sums (I don't know):

1    1.6
2    1.1
2    3.4
3    -1.3
3    6.0
3    1.1
4    -1.0
5    10.9

Edit: Thanks to Elenaher, we could say the input is the file above.

解决方案

$ awk -F"[: \t]+" '{a[$2]+=$NF}END{for(i in a ) print i,a[i] }' file
4 -1
5 10.9
1 1.6
2 4.5
3 5.8

这篇关于从CSV文件awk的条件求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆