我的数据文件的一部分看起来像
ifile.txt 1 1 3 0 6 3 0 3 3 5
我想find不包括零的每个数字的概率。 例如P(1)= 2/8; P(3)= 4/8等等
欲望输出
ofile.txt 1 0.250 3 0.500 5 0.125 6 0.125
第一列显示除0之外的唯一编号,第二列显示概率。 我正在尝试如下,但看起来非常冗长的想法。 我在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
在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
如何sort | uniq -c
sort | uniq -c
在sort | uniq -c
log n而不是n ^ 2时间内得到不同的数字计数,然后通过除以wc -l
总非零计数来运行。
以下是使用Novelocrat的sort|uniq -c
建议:
sed '/^0/ d' ifile.txt|sort|uniq -c >i awk 'FNR==NR{n+=$1;next;}{print $2,$1/n}' ii
简短的解释
从0的sed '/^0/ d' ifile.txt
删除数字
sort|uniq -c >i
给你i
:
2 1 4 3 1 5 1 6
在awk中, FNR==NR{n+=$1;next;}
总计i
在n
col 1( next
跳过下一个命令),然后print $2,$1/n
打印i
col 2和col 1的商n
。