简体   繁体   中英

Count value in shell script

I need help , i have a file 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.

Thanks a lot

You can do it with uniq and sort :

<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. however to get the same output format as described in question, try this awk line

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.

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 output.txt | uniq -c

Note: Only 'problem' is that the counts are in front of each occurrence and in your example after it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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