如何修改awk代码实现Bash中多列唯一值的统计?
awk多列非NA值计数代码修改
需求
原有awk代码实现的是两列维度下的唯一值计数,现在需要修改为支持多列统计:统计表格中DISa到DISi共9个DIS列的所有非NA值的出现次数。
原有两列统计代码
awk ' ##Starting awk program from here. BEGIN{ FS=OFS="\t" } !found[$0]++{ ##Checking condition if 1st and 2nd column is NOT present in found array then do following. val[$1]++ ##Creating val with 1st column inex and keep increasing its value here. } END{ ##Starting END block of this progra from here. for(i in val){ ##Traversing through array val here. print i,val[i] ##Printing i and value of val with index i here. } } ' Input_file ##Mentioning Input_file name here.
输入表格样例
patient sex DISa DISb DISc DISd DISe DISf DISg DISh DISi patient1 male 550.1 550.5 594.1 594.3 594.8 591 1019 960.1 550.1 patient2 female 041 208 250.2 276.14 426.32 550.1 550.5 558 041 patient3 female NA NA NA NA NA NA NA 041 NA
期望输出格式
550.1 3 550.5 2 594.1 1 594.3 1 594.8 1 591 1 1019 1 960.1 1 041 3 208 1 250.2 1 276.14 1 426.32 1 558 1
修改后多列统计实现代码
awk ' BEGIN{ FS=OFS="\t" } NR==1 {next} # 跳过表头行 { # 遍历DISa到DISi对应的第3到第11列 for(col=3;col<=11;col++){ if($col != "NA"){ count[$col]++ } } } END{ for(k in count){ print k, count[k] } } ' Input_file
代码说明
- 自动跳过表头行,不会把列名计入统计结果
- 遍历范围可根据实际DIS列的起止位置调整,不需要固定为9列
- 自动过滤所有取值为
NA的无效值,仅统计有效DIS值的出现次数 - 输入输出默认使用制表符分隔,和要求的格式匹配
内容的提问来源于stack exchange,提问作者ProfHariSeldon
相关产品推荐
相关产品推荐

