gpt4 book ai didi

shell - 使用条件分隔和计算列表中的元素数量

转载 作者:行者123 更新时间:2023-12-02 07:01:03 25 4
gpt4 key购买 nike

我想分离并计算输入列表中的元素数量。input.txt 包含 2 列,$1 是元素 ID,$2 是它的比率(数字)。

ENSG001 12.3107448237
ENSG007 4.3602275
ENSG008 2.9918420285
ENSG009 1.035588
ENSG010 0.999864
ENSG012 0.569833
ENSG013 0.495325
ENSG014 0.253893
ENSG015 0.125389
ENSG017 0.012568
ENSG018 -0.135689
ENSG020 -0.4938497942
ENSG022 -0.6429221854
ENSG024 -1.1759339381
ENSG029 -4.2722999766
ENSG030 -11.8447513281

我想将比率分为以下几类:

Greater than or equal to 2
Between 1 and 2
Between 0.5 and 1
Between -0.5 and 0.5
Between -1 and -0.5
Between -2 and -1
Less than or equal to 2

然后将每个类别的计数打印到一个单独的输出文件 results.txt 中:

Total   16
> 2 3
1 to 2 1
0.5 to 1 2
-0.5 to 0.5 6
-0.5 to -1 1
-1 to -2 1
< -2 2

我可以使用以下命令在命令行上执行此操作:

awk $2 > 2 {print $1,$2} input.txt | wc -l
awk $2 > 0.5 && $2 < 1 {print $1,$2} input.txt | wc -l
awk $2 > -0.5 && $2 < 0.5 {print $1,$2} input.txt | wc -l
awk $2 > -0.5 && $2 < -1 {print $1,$2} input.txt | wc -l
awk $2 > -1 && $2 < -0.5 {print $1,$2} input.txt | wc -l
awk $2 > -2 && $2 < -1 {print $1,$2} input.txt | wc -l
awk $2 < -2 {print $1,$2} input.txt | wc -l

我认为使用带 while 或 for 循环的 shell 脚本有一种更快的方法,但我不知道该怎么做。任何建议都会很棒。

最佳答案

你可以只处理一次文件,直接的方法是:

awk '$2>=2{a++;next}
$2>0.5 && $2 <1 {b++;next}
$2>-0.5 && $2 <0.5 {c++;next}
...
$2<=-2{x++;next}
END{print "total:",NR;
print ">2:",a;
print "1-2:",b;
...
print "<-2:",x
}' file

关于shell - 使用条件分隔和计算列表中的元素数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20633892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com