This is a test version of Biostars. For the public version, visit https://www.biostars.org.
how to keep fasta based on pattern in header.

Hi, I have a fasta file like this:

>NZ_CP012501.1 Escherichia coli strain 08-00022 plasmid pCFSAN004179G, complete sequence
GTTCTGGACGTACTGTGTCAGTGTGTCGATACCCCGGCGCATATCGACGGGTTTTACGACCAGGAATACG
TTATCAGGCGTCAGCATGGCGAAGAGCCCGGAAAACATCGGTTAACTGAGAAGGCTGGCAGCACATCCGG
ATACCTCCGGGAAGGAAAAGTGTGACAGGCTCATCCGACAATGGTCTGCCATCAGCCATACCGGGAGCGC
CAGACACTGAAACTGGAATAATTTCAGGTGCTCTGGCTCGTTTTTCGGCTTTTGCGACATCCTGCGGCCA

> mus musculus
TTTAAAAAGATATTATATATTA

> or whatever in the header
GGGGATATATTATATATATATAT

I want to keep in a multifasta only sequence belonging to coli. I tried several stuff using SeqIO or awk but it failed each time. Any idea? Thnaks!!!!

sequence

3 answers

 awk '/^>/ {ok=index($0,"Escherichia coli");} {if(ok) print;}' in.fasta

Hehe, we submitted nearly identical solutions at the same moment.

Great minds think alike :)

Thanks guys, it work perfectly!!!

You can do it with an awk one-liner if you like:

awk '/^>/{x = /Escherichia coli/;}(x)'

Mine is smaller ;-) (Things you won't hear T say)

Use the record separator variable RS in awk. For example:

$ awk 'BEGIN{ RS = ">"; } { if ($0 ~ /coli/) { printf ">"$0; } }' input.fa > coli.fa

Or:

$ awk 'BEGIN{ RS = ">"; } { if ($0 ~ /mus/) { printf ">"$0; } }' input.fa > mus.fa

Etc.

If you want to automate this with a shell variable:

$ export NEEDLE="mus"
$ awk -vneedle=${NEEDLE} 'BEGIN{ RS = ">"; } { if ($0 ~ needle) { printf ">"$0; } }' input.fa > needle.fa

Thanks for your help !!!!!!!

Log in to answer this question.