简体   繁体   English

在Shell脚本中计数值

[英]Count value in shell script

I need help , i have a file output.txt 我需要帮助,我有一个文件output.txt

ttl 128
ttl 128
ttl 128
ttl 128
ttl 1
ttl 128
ttl 255
ttl 1
ttl 64
ttl 128
ttl 128
ttl 1

i need count how many times appear the same value in the lines of the file. 我需要计算在文件行中出现相同值的次数。 The final result must be something like this: 最终结果必须是这样的:

ttl 128 - 7 times
ttl 64 - 1 time
ttl 255 - 1 time
ttl 1 - 3 times

I hope you can help me. 我希望你能帮助我。 I'm trying to use grep command. 我正在尝试使用grep命令。

Thanks a lot 非常感谢

You can do it with uniq and sort : 您可以使用uniqsort做到这一点:

<output.txt sort -V | uniq -c

Output: 输出:

3 ttl 1
1 ttl 64
7 ttl 128
1 ttl 255

sort, uniq are sufficient for this job. 排序,uniq足以胜任这项工作。 however to get the same output format as described in question, try this awk line 但是,要获得与上述问题相同的输出格式,请尝试以下awk行

awk '{a[$0]++}END{for(x in a){t=a[x]>1?"times":"time";print x " - "a[x],t}} file

for example 例如

  • the connector " - " 连接器“-”
  • if count >1 show times , otherwise time without s. 如果count> 1显示times ,否则time不带s。

output is: 输出为:

ttl 1 - 3  times
ttl 64 - 1 time
ttl 128 - 7  times
ttl 255 - 1 time

:) :)

You can use the sort command to sort your file and uniq to make it unique and count the occurrences: 您可以使用sort命令对文件和uniq进行排序,以使其唯一并计算出现次数:

 sort output.txt | uniq -c

Note: Only 'problem' is that the counts are in front of each occurrence and in your example after it. 注意:唯一的“问题”是计数在每个事件的前面,而在您的示例中是在此之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM