This is a test version of Biostars. For the public version, visit https://www.biostars.org.
How to sort fasta file numerically

Hi,

I was wondering if there was a way to sort a fasta file so that the chromosomes are in numeric order. Currently, the fasta file is computationally sorted where the chromosomes are order like this

>chr1
>chr10
>chr11
....
>chr2
>chr20

I was wondering if there was a way to sort the fasta file so the chromosomes are sorted numerically like this

>chr1
>chr2
>chr3
...
>chr10
>chr11
assembly genome sequence
$ seqkit sort -nN test.fa -o test_out.fa

1 answer

Try:

bioawk -c fastx '{print}' in.fa | sort -k1,1V | awk '{print ">"$1;print $2}'

or any of:

Sort Multiple Fasta Numerically

I saw that post. I tried Frédéric Mahé post and it doesn't appear to work. I can't seem to get Ih3 answer to work either

I edited my answer, please try again.

I believe it is because the orginal post has a different chromosome structure i.e ">chr2_1000-1020"

Yes, to make Frédéric Mahé answer work with your data, you need to change the -t field of the sort function so that it fits your fasta headers.

sort -t "r" -k2n for instance instead of sort -t "_" -k2n

sed -e '/>/s/^/@/' -e '/>/s/$/#/' file.fasta | tr -d "\n" | tr "@" "\n" | sort -t "r" -k2n | tr "#" "\n" | sed -e '/^$/d'

Log in to answer this question.