Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I have a column like this.

Streptococcus
Ecoli
Bcoli
Ecoli
streptococcus
Streptococcus
Mycobacterium
Ecoli

I want a file like this (which includes all unique values and their corresponding counts)

Streptococcus 3
Ecoli 3
Bcoli 1
Mycobacterium 1

Can anyone please help in getting it in ubuntu 12.04?

share|improve this question
1  
Which language? shell, c, python.. any? –  Sneetsher Jul 5 at 10:49

2 Answers 2

Assuming each item appears on another line, here is a python solution. Of course you can write the result to a file instead of printing it.

#!/usr/bin/env python
sourcefile = "/path/to/sourcefile"

with open(sourcefile, "r") as germ:
    germ = [item.lower().replace("\n", "") for item in germ.readlines()]
for item in sorted(set(germ)):
    print item.title(), germ.count(item)

it gives:

Bcoli 1
Ecoli 3
Mycobacterium 1
Streptococcus 3

To use it

paste the code above in an empty textfile, save it as get_uniques.py, make it executable (for convenience reasons, so you don't need to type the language if you run it) and run it in a terminal window by the command:

/path/to/get_uniques.py

In case you'd like to write it to a file directly

Use the code below:

#!/usr/bin/env python
sourcefile = "/path/to/sourcefile"
destfile = "/path/to/destinationfile"

with open(sourcefile, "r") as germ:
    germ = [item.lower().replace("\n", "") for item in  germ.readlines()]
with open(destfile, "wt") as germcount:
    for item in sorted(set(germ)):
        germcount.write(item.title()+" "+str(germ.count(item))+"\n")
share|improve this answer
    
you don't need to make the .py file executable. Just running python file.py is enough. And also don't give the short form of input file path in .py file. Short form means ~/Desktop. If you do like so then it gives an error. So path should be in expanded form. –  Avinash Raj Jul 5 at 12:21

Using sort and uniq,

$ sort f | uniq -ci | awk '{print $2,$1}'
Bcoli 1
Ecoli 3
Mycobacterium 1
streptococcus 3
share|improve this answer
1  
Or you can simply pass -i option to uniq to ignore case if needed. It would be uniq -ci. –  Mahdi Jul 5 at 10:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.