gpt4 book ai didi

bash - 分组并过滤结果

转载 作者:行者123 更新时间:2023-11-29 09:39:29 25 4
gpt4 key购买 nike

我有一个用管道分隔的文件,我必须按字段进行分组并获取其出现次数的总和。

我的输入文件看起来像:

96472|Text1|6|A|City|Austin, TX|0123|9899|2017-02-12
96472|Text1|6|A|City|Austin, TX|0123|9899|2017-02-12
96472|Text1|6|A|City|Austin, TX|0123|9899|2017-02-12
214126|Text1|6|A|City|Austin, TX|0123|9899|2017-02-12
214126|Text1|6|A|City|Austin, TX|0123|9899|2017-02-12
214126|Text1|6|A|City|Austin, TX|0123|9899|2017-02-12
214126|Text1|6|A|City|Austin, TX|0123|9899|2017-02-12
214126|Text1|6|A|City|Austin, TX|0123|9899|2017-02-12
214126|Text1|6|A|City|Austin, TX|0123|9899|2017-02-12
214126|Text1|6|A|City|Austin, TX|0123|9899|2017-02-12
214126|Text1|6|A|City|Austin, TX|0123|9899|2017-02-12
214126|Text1|6|A|City|Austin, TX|0123|9899|2017-02-12
214126|Text1|6|A|City|Austin, TX|0123|9899|2017-02-12

我是这样做的:

cut -d'|' -f1 somefile.txt | cut -d'-' -f1 | sort | uniq -c 
output is
3 96472
10 214126

本质上是想对一个字段的出现进行总结,就像sql中的group by子句一样。所以在我的示例中,我显示字段/列 1 的重复值为 3 和 10

我相信有更好的方法来做到这一点。而且我还想过滤出现次数少于 10 次的记录:

cut -d'|' -f1 somefile.txt | cut -d'-' -f1 | sort | uniq -c | grep -v 10

有什么好的方法可以兼顾吗?

最佳答案

与使用其他实用程序相比,一个简单的 awk 逻辑就足够了。对于您的输入文件,输出如下;

awk -F"|" '{count[$1]++}END{for (i in count) print count[i],i}' file
3 96472
10 214126

想法是 count[$1]++ 增加文件中 $1 的出现次数,一旦文件被处理,END子句打印出 $1

中每个唯一字段的总数

另一个过滤器只列出小于 10 的那些

awk -F"|" '{count[$1]++}END{for (i in count) if (count[i] < 10){print count[i],i}}' file
3 96472

关于bash - 分组并过滤结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41443087/

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