对这样格式的数据怎么统计啊?

sh/bash/dash/ksh/zsh等Shell脚本
回复
mushroom09
帖子: 16
注册时间: 2009-08-13 16:57

对这样格式的数据怎么统计啊?

#1

帖子 mushroom09 » 2009-10-30 11:46

格式如下的数据:
A:
test1:1
test2:1
----------------------
B:
test1:1
test2:2
---------------------
A:
test1:1
test2:2
----------------------
.
.
-------------------------
最终结果要
A:
test1:total
test2:total
--------------------------
B:
test1:total
test2:total
要分别统计A,B下各有多少个test1,test2
怎么解决啊?请高手指教 :em06
mushroom09
帖子: 16
注册时间: 2009-08-13 16:57

Re: 对这样格式的数据怎么统计啊?

#2

帖子 mushroom09 » 2009-10-30 17:11

没人知道吗? :em20
头像
Ur@nus
帖子: 622
注册时间: 2006-12-01 23:02

Re: 对这样格式的数据怎么统计啊?

#3

帖子 Ur@nus » 2009-10-30 19:47

我有个bash的思路,sed 把
A;
test1:*
找到,然后删掉
A:
test1:
把剩下的作为输入打印到某文件,cat 和for配合逐个付给变量再累加

对语test2
A:
test1:*
test2:*
删除
A:
test1:*
test2:
类推


具体脚本我的回去想象.说实话,sed用的不好还得查文档. :em20
等等哪些脚本党看看能不能帮你.
头像
xiooli
帖子: 6956
注册时间: 2007-11-19 21:51
来自: 成都
联系:

Re: 对这样格式的数据怎么统计啊?

#4

帖子 xiooli » 2009-10-30 20:27

代码: 全选

awk -F":" '/A:/{flag="A:"};/B:/{flag="B:"};/^[AB-]/{$0=""};$0 != ""{$0=flag$0};/A:test1/{sumA1+=$3};/A:test2/{sumA2+=$3};/B:test1/{sumB1+=$3};/B:test2/{sumB2+=$3};END{print "A:\ntest1:"sumA1"\ntest2:"sumA2"\nB:\ntest1:"sumB1"\ntest2:"sumB2}' file
头像
xzap
帖子: 256
注册时间: 2006-08-24 21:25

Re: 对这样格式的数据怎么统计啊?

#5

帖子 xzap » 2009-10-30 20:31

输出A的和

代码: 全选

awk -F":" 'NF==2&&$1=="A"{num=NR+1} NR==num{test1+=$2};NR==num+1{test2+=$2}END{print "A:\ntest1:"test1"\ntest2:"test2}' filename
输出B的和

代码: 全选

awk -F":" 'NF==2&&$1=="B"{num=NR+1} NR==num{test1+=$2};NR==num+1{test2+=$2}END{print "B:\ntest1:"test1"\ntest2:"test2}' filename
不好意思,随便乱回答的。仅供参考吧。awk我也不是很熟

合在一起

代码: 全选

awk -F":" 'NF==2&&$1=="A"{num=NR+1} NR==num{atest1+=$2};NR==num+1{atest2+=$2};NF==2&&$1=="B"{num2=NR+1};NR==num2{btest1+=$2};NR==num2+1{btest2+=$2}END{print "A:\ntest1:"atest1"\ntest2:"atest2"\nB:\ntest1:"btest1"\ntest2:"btest2}' filename

没看到 xiooli 回答了,用他的吧,我awk不熟的,我是瞎写的。
mushroom09
帖子: 16
注册时间: 2009-08-13 16:57

Re: 对这样格式的数据怎么统计啊?

#6

帖子 mushroom09 » 2009-11-02 16:48

咱大牛一个,今天学习了哈哈

还有一个问题,对test1,test2能否用变量来取代?就是在模式匹配的是引用外部变量
写成大概这种效果:
for var in var1,var2,var3
do
awk ' /A:$var/{action} '
done
大概这个意思,awk不会用 :em06
mushroom09
帖子: 16
注册时间: 2009-08-13 16:57

Re: 对这样格式的数据怎么统计啊?

#7

帖子 mushroom09 » 2009-11-02 17:03

解决了,谢谢大牛们了哈哈哈
awk 不错 :em01
头像
xzap
帖子: 256
注册时间: 2006-08-24 21:25

Re: 对这样格式的数据怎么统计啊?

#8

帖子 xzap » 2009-11-02 20:06

楼主你发的viewtopic.php?f=21&t=235668这个帖子我告诉过你如何引用外部变量了阿。
用awk -v或者"'$var'"
没话讲了
回复