首页 > 解决方案 > 用于根据多个条件计算记录的 awk 脚本

问题描述

我有一个包含 3 列的文件,如下所示

col1,col2
a,x,1
b,y,2
a,x,0
b,x,2
b,y,0
a,y,0

我正在编写一个 awk 脚本以获得以下输出:(按 col1 和 col2 以及总数、条件 1、条件 2 分组)

col1,col2,total count,count where col3=0, count where col3>0
a,x,2,1,1
a,y,1,1,0
b,x,1,0,1
b,y,2,1,1

我制定了一个脚本,通过使用以下命令分别获取所有 3 个:

for case 3 : col3>0
awk -F',' '($3>0)NR>1{arr[$1","$2]++}END{for (a in arr) print a, arr[a]}' file 

其他情况的类似命令也是如此。

我无法创建命令/脚本来同时解决所有 3 种情况。

任何帮助表示赞赏。

PS:这个示例文件很小,所以我可以运行 3 个脚本/命令并加入它们,但对于真正的文件太大,无法运行相同的瘦 3 次。

标签: awk

解决方案


这是一个:

$ awk '
BEGIN {                        
    FS=OFS=","                 # field separators
}
NR>1 {                         # after header
    k=$1 OFS $2                # set the key
    a[k]++                     # total count of unique $1 $2
    b[k]+=($3==0)              # count where $3==0
    c[k]+=($3>0)               # count where $3>0
}
END {                          # after all processing is done
    for(i in a)                # output values
        print i,a[i],b[i],c[i]
}' file

输出(以随机顺序,但您可以在评论中使用@Inian 的提示修复它):

a,y,1,1,0
b,x,1,0,1
b,y,2,1,1
a,x,2,1,1

推荐阅读