awk - 用于根据多个条件计算记录的 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 '
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
推荐阅读
- powershell - Powershell选择不在的地方
- android - Android:自定义textView中的文本不居中
- oauth-2.0 - 如何在测试中调用 Google Account Linking?
- matlab - 任何相当于fitdist的Octave?
- com - 用新的托管 COM 可调用程序集替换 COM DLL
- javascript - queryselector 为输入字段返回不正确的值
- javascript - 赛普拉斯 - 如何在另一个请求标头中使用响应正文
- r-markdown - 我正在使用 rmarkdown::render(my_file.Rmd) 渲染 beamer_presentation 擦除了我计算机上的所有内容
- javascript - 如何根据Angular中另一个对象的属性过滤对象数组?
- django - 在 django 中更改模型的自定义保存方法中的其他对象