# Remove/delete sequences by ID from multifasta

I have a fasta file like this:

>Id1
ATCCTT
>Id2
ATTTTCCC
>Id3
TTTCCCCAAAA
>Id4
CCCTTTAAA


I want to delete sequences that have the following IDs.

Id2
Id3


The IDs are in a .txt file, and the text file will be used to match and delete those sequences.

My output should be a fasta file like this

>Id1
ATCCTT
>Id4
CCCTTTAAA


But I want it with awk and/or sed and/or bash (no python or perl).
How can I do it?

• why the language restrictions? – Chris_Rands Mar 20 '18 at 19:03
• Exactly: use the right tool for the job. Unless you can make some very strong assumptions about your input files, use a proper FASTA parser, not some hacked-together cruft. – Konrad Rudolph Mar 23 '18 at 9:11
• Use whatever tool you want to use if it gets your work done before a deadline. A lot of parsers are slow as mud as compared with Unix tools, but I admit they take a lot of drudgery out of understanding how things work. – Alex Reynolds Mar 26 '18 at 5:00

Just today I wrote a script to do exactly this using Biopython. I also add a warning If any the headers I wanted to filter was not present in the original fasta. So the python script filter_fasta_by_list_of_headers.py is :

#!/usr/bin/env python3

from Bio import SeqIO
import sys

ffile = SeqIO.parse(sys.argv[1], "fasta")
header_set = set(line.strip() for line in open(sys.argv[2]))

for seq_record in ffile:
try:
except KeyError:
print(seq_record.format("fasta"))
continue
print(len(header_set),'of the headers from list were not identified in the input fasta file.', file=sys.stderr)


and usage :

filter_fasta_by_list_of_headers.py input.fasta list_of_scf_to_filter > filtered.fasta


P.S. it's quite easy to turn over the script to extract the sequences from the list (just the print line would have to move after line header_set.remove(seq_record.name)

• They said no python, but don't know why. Ignoring that, my intuition is that doing if seq_record.name in header_set: etc. will be better for this case assuming the majority of records are to print. Error handling is kinda expensive and LBYL seems likely faster than EAFP here – Chris_Rands Mar 21 '18 at 16:04
• AH, I missed the "no python" request. The speedup tip sounds good (although it's not really a piece of code that needs to be obtimised, it parsed about a hundred thousand of contigs (while filtering a few contaminants) in like 2 minutes?) – Kamil S Jaron Mar 21 '18 at 16:31
• +1 for ignoring nonsensical requirements and using the proper tool. That said, I’m not too sure about the performance of this approach. Using errors in this way is idiomatic in Python but it still comes at a cost. A simple in test is probably a lot more efficient; it might even be unnecessary to remove the entries, which can also be very costly. – Konrad Rudolph Mar 23 '18 at 9:12
• @KonradRudolph Alright, so I made a modification you have suggested and bench marked it on normal insect genome assembly - 1Gbp, 300,000 scaffolds and I gave it lists of 5,000 and 100,000 scaffolds to filter. Regardless on the size of the list or algorithm used it took 29-30s. In other words, if LBYL is faster than EAFP, it's on a scale that totally does not matter. – Kamil S Jaron Mar 23 '18 at 13:07
• @KamilSJaron Nice! – Konrad Rudolph Mar 23 '18 at 13:30

If you want to learn how to do things with command-line tools, you can linearize the FASTA with awk, pipe to grep to filter for items of interest named in patterns.txt, then pipe to tr to delinearize:

$awk '{ if ((NR>1)&&($0~/^>/)) { printf("\n%s", $0); } else if (NR==1) { printf("%s",$0); } else { printf("\t%s", $0); } }' in.fa | grep -Ff patterns.txt - | tr "\t" "\n" > out.fa  This will work on multiline FASTA. Suppose you keep sequence names in ids.txt and sequences in seq.fa: awk 'BEGIN{while((getline<"ids.txt")>0)l[">"$1]=1}/^>/{f=!l[\$1]}f' seq.fa


Using the FastaToTbl and TblToFasta scripts I have posted before, you can do:

FastaToTbl file.fa | grep -vwf ids.txt | TblToFasta > file.2.fa


Presume grep is OK if sed, awk are. The -A(n) and -B(n) flags give (n) lines post match. Presuming all your fasta sequence will be one line is a bit dangerous, but it works for your example. First get those IDs to be removed (in rmid.txt), then inverse grep against the initial fasta.

grep -A1 -f rmid.txt fasta.fa > rmfile.fa
grep -v -f rmfile.fa fasta.fa


The real answer is to use a script that defines a delimiter other than newline "\n", then parse for IDs, so better to use one of the languages you don't want to use...

• This assumes only one line of sequence per ID which is not likely true for fasta files (but is often true of fastq). – terdon Mar 20 '18 at 18:59
• The problem with greping Id1 is substrings, this will also capture Id10 etc. you could add --word-regexp flag, but this can often really hurt performance; awk probably a better tool – Chris_Rands Mar 20 '18 at 19:02
• Yes, both good points, example is still completed as per request. @terdon I specified line number as an issue, \@Chris_Rands unlikely that fasta IDs would be formed to allow that kind of issue but point appreciated. FWIW, for manipulating fasta I would not use grep, awk, sed, there are plenty of good packages based around scripting languages, I would favour Bioperl. I am a lowly newcomer so couldn't comment this to OP. – user1141 Mar 20 '18 at 19:15
• Ah, so you did. Sorry, I missed the disclaimer and only saw the command. However, note that having having IDs be substrings of other IDs is absolutely common. For instance, the standard human genome fasta sequence has both chr1 and chr11. That said, your answer has a much more serious issue: each line of rmfile.fa will be passed to grep as a pattern to search for, so any line containing that will be removed. This means that if sequence id3 is TAT, you will remove all lines matching TAT irrespective of their ID. – terdon Mar 20 '18 at 19:21