Litox
Litox

Reputation: 163

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

Upvotes: 1

Views: 700

Answers (3)

Kent
Kent

Reputation: 195049

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

:)

Upvotes: 3

Veger
Veger

Reputation: 37905

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.

Upvotes: 0

Thor
Thor

Reputation: 47099

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

Upvotes: 4

Related Questions