I have a problem: I've managed to download a massive fasta file of 1500 sequences, but now I want to split them into separate fasta files based on the genus.

The fasta file looks like this:

>YP_009300697.1 terminase large subunit [Arthrobacter phage Mudcat]

>YP_009208724.1 hypothetical protein ADP65_00072 [Achromobacter phage phiAxp-3]

>YP_009148449.1 large terminase subunit [Delftia phage RG-2014]

I would like to end up with something like this:

>Mycobacterium phage JAMaL

>Mycobacterium phage Bruin

>Mycobacterium phage Zaka

>Salmonella virus SETP7

>Salmonella virus SE2
and so on...

So that the label on the alignment would have the name of the phage and not the protein's ID.

I've managed to extract the genus names of my organism with this:

outfile = open('species.txt', 'w')
with open('terminase_large.fasta') as fd:
    for line in fd:
        if line.startswith('>'):
            if '[' in line:
                name=name.split(' ', 1)[0]
                outfile.write(name[:] + "\n")

And got to extract only the unique names with this:

lines_seen = set()
outfile = open('species2.txt', "w")
for line in open("species.txt", "r"):
    if line not in lines_seen:  # not a duplicate

(Can I merge those two scripts together?)

Now, my genus names look like this:


I tried automating my script to get the Entrez data, but it gives me the 'Supplied id parameter is empty' message

My code looks like this:

from Bio import Entrez
Entrez.email = "[email protected]"

for line in open("species2.txt", "r"):
    searchterm = "(terminase large subunit AND viruses[Organism]) AND" +line+ "AND refseq[Filter]"
    searchResultHandle = Entrez.esearch(db="protein", term=searchterm, retmax=1000)
    searchResult = Entrez.read(searchResultHandle)
    ids = searchResult["IdList"]

    handle = Entrez.efetch(db="protein", id=ids, rettype="fasta", retmode="text")
    record = handle.read()

    out_handle = open('terminase_large_'+str(line[:-1])+'.fasta', 'w')

Can someone help me with it?

  • $\begingroup$ Please edit your question and i) show us a short example of your input file, including different genera and ii) show us the output you would expect from that file. That way, we can test our solutions and be sure to give you what you need. $\endgroup$
    – terdon
    Commented Jul 31, 2017 at 9:48
  • $\begingroup$ Also, you seem to have bacterial genera, why are you searching for viruses? Of course that won't find any results. $\endgroup$
    – terdon
    Commented Jul 31, 2017 at 9:49
  • $\begingroup$ My keywords use the bacteria genera and the virus as organism, since I want specific phages that infect bacteria, eg Enterobacter phage or Vibrio phage $\endgroup$
    – tahunami
    Commented Jul 31, 2017 at 9:55
  • $\begingroup$ Ah yes, sorry, I thought you were specifying the bacterial genus as [ORGANISM] as well. So, is it enough to parse the existing file or do you need your script to be modified to create the multiple files next time it runs? Modifying the existing one and splitting it into subfiles by genus is very easy. Would that be enough? $\endgroup$
    – terdon
    Commented Jul 31, 2017 at 10:05
  • $\begingroup$ @terdon sure, I just didn't know which was easier: splitting the existing file, which has the genera mixed up or creating a new fasta file by searching Entrez $\endgroup$
    – tahunami
    Commented Jul 31, 2017 at 10:07

2 Answers 2


Splitting into multiple files and changing the IDs can be easily done:

perl -pe 'if(/>/){/\[(.*?)\]\s*$/; $_="> $1\n"}' file.fa | 
    awk '(/^>/){name=$2} {print >> name".fa"}'

That assumes all your FASTA headers have [foo bar baz] as the last element of a line. It will create a file called foo.fa (the bacterium's name) with all sequences saved there.


  • perl -pe : run the script given by -e on each line of the input file, and print the resulting line.
  • if(/>/) : if this line starts with a >. \
  • /\[(.*?)\]\s*$/ : match an opening bracket (\[), then capture (that's what the parentheses do, they capture a pattern so we can refer to it as $1) everything until the first ] (.*?\])
  • $_="> $1\n" : the $_ special variable in Perl is (in this case) the current line. So, $_=foo means "make the current line read foo. Since the -p prints each input line, changing the value of $_ means the changed value will be printed. So here, we are printing >, whatever was in the square brackets ($1) and a newline character.

The output of the perl command alone on your example input file is:

$ perl -pe 'if(/>/){/\[(.*)\]\s*$/; $_="> $1\n"}' file.fa
> Arthrobacter phage Mudcat

> Achromobacter phage phiAxp-3

> Delftia phage RG-2014

So, we now pass it through awk which does:

  • (/^>/){a=$2} : if this line starts with an >, save the second field (the bacterial species) as the variable name.
  • {print >> name".fa"} : print each line into a file whose name is the current value of the variable name with a .fa. extension.

If you prefer python scripts to the one-liner approach, you can do the same thing with:

#!/usr/bin/env python
import re
outFile = None
with open("file.fa", "r") as inFile, open(species + ".fa", 'a') as outFile:
    for line in inFile:
        line = line.rstrip()
        if line.startswith('>'):
            regex = re.compile('.*\[((.+?)\s+.*?)\].*')
            matches = regex.search(line)
            species = matches[2]
            outFile.write('>%s\n' % matches[1])
            outFile.write("%s\n" % line)

As for your script, you've got the right idea, but have a small bug. You forgot to remove the \n from your input file, so it looks for Arthrobacter\n instead of Arthrobacter. The golden rule of debugging is "print all the things". If you add print("Searchterm: ",searchterm) you will see:

Searchterm:  (terminase large subunit AND viruses[Organism]) ANDArthrobacter  
AND refseq[Filter]
Searchterm:  (terminase large subunit AND viruses[Organism]) ANDAchromobacter  
AND refseq[Filter]
Searchterm:  (terminase large subunit AND viruses[Organism]) ANDDelftia  
AND refseq[Filter]

So, you need to remove the newline characters and add a space like so (I also made it a bit more "pythonic" and conforming to the Python syntax guidelines):

#!/usr/bin/env python
from Bio import Entrez
Entrez.email = "[email protected]"

with open("species2.txt", "r") as in_handle:
    for line in in_handle:
        line = line.rstrip()
        searchterm = ("(terminase large subunit AND viruses[Organism]) " +
                      "AND %s AND refseq[Filter]" % line)
        print("Searchterm: ", searchterm)
        searchResultHandle = Entrez.esearch(db="protein",
                                            term=searchterm, retmax=1000)
        searchResult = Entrez.read(searchResultHandle)
        ids = searchResult["IdList"]

        handle = Entrez.efetch(db="protein", id=ids,
                               rettype="fasta", retmode="text")
        record = handle.read()

        with open('terminase_large_' + str(line[:-1]) + '.fasta', 'w') as out_handle:
  • $\begingroup$ Is it possible to do the perl script in python? I don't have perl on my pc installed. About the second part: it works! Sort of. When I debug my script I can see that python gets the desired fasta file (a url link is created), and it creates a file with the correct name, but somehow doesn't input the data into it $\endgroup$
    – tahunami
    Commented Jul 31, 2017 at 10:55
  • $\begingroup$ @tahunami what do you mean, unless you're using Windows, it should be installed by default. Are you sure it's not installed? $\endgroup$
    – terdon
    Commented Jul 31, 2017 at 10:57
  • $\begingroup$ I've saved in itno a .pl file, and run it on perl, but got "Execution of split.pl aborted due to compilation errors" $\endgroup$
    – tahunami
    Commented Jul 31, 2017 at 11:10
  • 2
    $\begingroup$ @tahunami no, that is a one-liner. Don't save as a file, just paste it directly into an open terminal. That's just a *nix command. In any case, I also added a python version for you. $\endgroup$
    – terdon
    Commented Jul 31, 2017 at 11:17

A (bio)awk-based solution

Generate the list of genus

bioawk -c fastx '{print $comment}' terminase_large.fasta \
    | sed -r 's/.*\[(\w+).*/\1/' \
    | sort -u > genus_names.txt

Here is how it works:

  1. bioawk is like awk but with extra parsing capabilities. -c fastx parses the fields in fasta or fastq records. {print $comment} will print the $comment field which contain the genus names you want to extract.

  2. The sed command captures (with parentheses) the word (\w+) that is just after the opening square bracket (which should be the genus name, if there is only one opening square bracket on the line), and substitutes the whole line (that is, everything before the bracket (.*), the bracket (\[), the word, and everything after the word (.* again)) with just the captured word (\1).

  3. All this is sorted, and the -u option of sort ensures there is only one occurrence of each genus name in the output, which we put in the genus_names.txt file.

Extract the fasta records for each genus

for genus in $(cat genus_names.txt)
    bioawk -c fastx '{print}' terminase_large.fasta \
        | grep ${genus} \
        | awk -F "\t" '{print ">"$4"\n"$2}' \
        | sed -r 's/^>[^\[]+\[(.*)\]/>\1/' > ${genus}.fasta

Here is how it works:

  1. We loop on the content of the previously established list of genus names.

  2. For each value of ${genus}, we parse again the fasta file with bioawk. This time, for a given fasta record, we print all the elements that have been parsed. They appear on one line, in the following order (according to bioawk -c help): 1:name 2:seq 3:qual 4:comment (we actually only need seq and comment for the following steps, but there are less risks of making errors at the later awk step if we keep the four fields).

  3. We use grep to select the resulting lines that contain the genus name we're currently dealing with.

  4. The lines that have been successfully selected are then parsed by awk and reformatted into fasta format using only the comment part in the header. The -F "\t" is to indicate that the field delimiters are tabulations (which is how bioawk has written the records when we did {print}).

  5. We use sed to keep only the part inside the square brackets (again using a pattern capture between parentheses, that we use in the substitution part with \1), and the output is written in a file named using the current value of ${genus}.

More details on the last sed command:

We match the whole header lines. They start with ">" (^>), then there are some non-"[" characters ([^\[]+), then a "[" (\[), then something we capture ((.*)), then a "]" (\]). We replace them with the captured part. The sequence lines are unaffected because they don't match the above regular expression.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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