使用 shell 脚本计算列中的唯一值

发布于 2024-08-31 17:19:06 字数 245 浏览 4 评论 0原文

我有一个包含 5 列的制表符分隔文件,需要检索第 2 列中唯一行数的计数。我通常会使用 Perl/Python 执行此操作,但我被迫使用 shell。

我过去曾成功使用 *nix uniq 函数通过管道传输到 wc,但看起来我必须在这里使用 awk。

任何建议将不胜感激。 (我之前问过一个关于使用 awk 进行列检查的类似问题,但这有点不同,我想将它分开,所以如果将来有人有这个问题,这将在这里)

非常感谢!
礼来公司

I have a tab delimited file with 5 columns and need to retrieve a count of just the number of unique lines from column 2. I would normally do this with Perl/Python but I am forced to use the shell for this one.

I have successfully in the past used *nix uniq function piped to wc but it looks like I am going to have to use awk in here.

Any advice would be greatly appreciated. (I have asked a similar question previously about column checks using awk but this is a little different and I wanted to separate it so if someone in the future has this question this will be here)

Many many thanks!
Lilly

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

呆° 2024-09-07 17:19:06

无需使用 awk。

$ cut -f2 file.txt | sort | uniq | wc -l

应该这样做。

这利用了 tab 是 cut 的默认字段分隔符这一事实,因此我们将通过这种方式仅获取第二列的内容。然后,通过 sort 作为 uniq 的前置阶段,删除重复项。最后我们计算行数,这就是所寻求的数字。

No need to use awk.

$ cut -f2 file.txt | sort | uniq | wc -l

should do it.

This uses the fact that tab is cut's default field separator, so we'll get just the content from column two this way. Then a pass through sort works as a pre-stage to uniq, which removes the duplicates. Finally we count the lines, which is the sought number.

清醇 2024-09-07 17:19:06

我选择

$ cut -f2 file.txt | sort -u | wc -l

至少在某些版本中,uniq 依赖于正在排序的输入数据(它只查看相邻行)。

例如,在 Solaris 文档 :

uniq 实用程序将读取输入
文件比较相邻行,以及
将每个输入行写一份副本
输出。第二次及后续
重复相邻输入的副本
行将不会被写入。

输入中的重复行不会
如果它们不相邻,则会被检测到。

I go for

$ cut -f2 file.txt | sort -u | wc -l

At least in some versions, uniq relies on the input data being sorted (it looks only at adjacent lines).

For example in the Solaris docs:

The uniq utility will read an input
file comparing adjacent lines, and
write one copy of each input line on
the output. The second and succeeding
copies of repeated adjacent input
lines will not be written.

Repeated lines in the input will not
be detected if they are not adjacent.

弥繁 2024-09-07 17:19:06
awk '{if($0~/Not Running/)a++;else if($0~/Running/)b++}END{print a,b}' temp
awk '{if($0~/Not Running/)a++;else if($0~/Running/)b++}END{print a,b}' temp
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文