Kay*_*Kay 3 unix linux shell awk probability-density
我的部分数据文件看起来像
ifile.txt
1
1
3
0
6
3
0
3
3
5
Run Code Online (Sandbox Code Playgroud)
我想找出除零之外的每个数字的概率.例如P(1)= 2/8; P(3)= 4/8,依此类推
欲望输出
ofile.txt
1 0.250
3 0.500
5 0.125
6 0.125
Run Code Online (Sandbox Code Playgroud)
第1列显示除0和第2列之外的唯一数字显示概率.我正在尝试如下,但看起来非常冗长的想法.我在for循环中遇到问题,因为有很多唯一的数字
n=$(awk '$1 > 0 {print $0}' ifile.txt | wc -l)
for i in 1 3 5 6 .....
do
n1=$(awk '$1 == $i {print $0}' ifile.txt | wc -l)
p=$(echo $n1/$n | bc -l)
printf "%d %.3f\n" "$i $p" >> ofile.txt
done
Run Code Online (Sandbox Code Playgroud)
使用关联数组awk
可以在一次通过中获取每个唯一编号的计数.
awk '$0 != "0" { count[$0]++; total++ }
END { for(i in count) printf("%d %.3f\n", i, count[i]/total) }' ifile.txt | sort -n > ofile.txt
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
153 次 |
最近记录: |