<p>One &quot;out there&quot; approach you could take is to create a fasta file containing your regions of interest (as separate sequences), and then map your fasta files to that reference fasta file, generating BAM/SAM output. After that, position-sort the BAM file, and you've now got a content-sorted list of sequences.</p>
<p>The process to do this would be something like this:</p>
<pre><code>minimap2 -a regions.fasta input1.fasta input2.fasta ... | samtools sort &gt; mapped.bam
samtools fastq mapped.bam &gt; sorted.fasta
</code></pre>

CC BY-SA 4.0
2020-10-30T20:00:09.343Z
2020-10-30T20:00:09.343Z
gringer
<p>The general idea is:</p>
<ol>
<li>iterate over all files
<ol>
<li>read the first line of each file, extract the <code>segment</code> bit</li>
<li>move the file based on that</li>
</ol>
</li>
</ol>
<p>In Python, this can be done in many ways. Here’s one way:</p>
<pre class="lang-py prettyprint-override"><code>import os
import re


def find_segment(id):
    return re.search(r'segment (\d)', id).group(1)


for segment in range(8):
    os.mkdir(f'segment-{segment + 1}')

for entry in os.scandir():
    if not entry.is_file():
        continue

    with open(entry.path, 'r') as file:
        segment = find_segment(next(file))
    os.rename(entry.path, f'segment-{segment}/{entry.path}')
</code></pre>
<p>Note the absence of error handling — this code assumes that every operation succeeds; empty files, or files without “<code>segment X</code>” in their FASTA ID, will trigger an error, as will the usual IO failures (missing permissions, etc.).</p>
<hr />
<p>But most people would probably use a shell scripting language instead of Python to solve this. For example, here’s something equivalent in Bash (untested):</p>
<pre class="lang-bash prettyprint-override"><code>mkdir segment-{1..8}

for file in *.fa *.fasta; do
    segment=<span class="math-container">$(sed 's/.*segment \([[:digit:]]\).*/\1/; q' "$</span>file&quot;)
    if [[ -n <span class="math-container">$segment ]]; then
    mv "$</span>file&quot; &quot;segment-$segment&quot;
    done
done
</code></pre>

CC BY-SA 4.0
2020-12-17T15:43:41.637Z
Very cool code.
M__
CC BY-SA 4.0
2020-10-29T10:19:46.490Z
2020-12-17T11:05:16.237Z
2020-12-17T11:05:16.237Z
Konrad Rudolph
<p>I have around 10,000 FASTA files of Influenza A virus.</p>
<p>These files contains sequences of each of the 8 segments of the viral genome and I want to separate each genome segment into a different folder and subdivide each directory into different files based on their geographic region of isolation.</p>
<p>In each FASTA file for each segment,the first line has the segment number, for example.</p>
<blockquote>
<p>KM368312.1 Influenza A virus (A/swine/Shandong/01/2009(H1N1)) segment 3 polymerase PA (PA) and PA-X protein (PA-X) genes, complete cds</p>
</blockquote>
<p>To be clear I want</p>
<ul>
<li>file1.txt has segment 1</li>
<li>file2.txt has segment 2
etc ...</li>
</ul>
<p>I want to ensure all segment 1 sequences are grouped into one folder, and each file is grouped according to its geographic origin. The geographic groupings are mirrored for all 8 segements and each placed into their own directory.</p>

CC BY-SA 4.0
2020-10-29T10:19:17.267Z
Cross-posted at https://stackoverflow.com/questions/64586925/how-to-sort-multiple-fasta-files-based-on-their-content?noredirect=1 (closed now).
tripleee
<python><covid-19><virus>
How to sort multiple FASTA files based on their content?
# How to sort multiple FASTA files based on their content?

(Asked by: username_0 on 2020-10-29)

I have around 10,000 FASTA files of Influenza A virus.

These files contains sequences of each of the 8 segments of the viral genome and I want to separate each genome segment into a different folder and subdivide each directory into different files based on their geographic region of isolation.

In each FASTA file for each segment,the first line has the segment number, for example.

> KM368312.1 Influenza A virus (A/swine/Shandong/01/2009(H1N1)) segment 3 polymerase PA (PA) and PA-X protein (PA-X) genes, complete cds

To be clear I want

* file1.txt has segment 1
* file2.txt has segment 2
  etc ...

I want to ensure all segment 1 sequences are grouped into one folder, and each file is grouped according to its geographic origin. The geographic groupings are mirrored for all 8 segements and each placed into their own directory.

**Tags:** python, covid-19, virus
> **Comments:**
> **username_1**: Cross-posted at https://stackoverflow.com/questions/64586925/how-to-sort-multiple-fasta-files-based-on-their-content?noredirect=1 (closed now).  

---

## 2 answers

### Answer by username_3 on 2020-10-29. Score: 4 | Accepted answer

The general idea is:

iterate over all files

read the first line of each file, extract the segment bit
move the file based on that



In Python, this can be done in many ways. Here’s one way:
import os
import re


def find_segment(id):
    return re.search(r'segment (\d)', id).group(1)


for segment in range(8):
    os.mkdir(f'segment-{segment + 1}')

for entry in os.scandir():
    if not entry.is_file():
        continue

    with open(entry.path, 'r') as file:
        segment = find_segment(next(file))
    os.rename(entry.path, f'segment-{segment}/{entry.path}')

Note the absence of error handling — this code assumes that every operation succeeds; empty files, or files without “segment X” in their FASTA ID, will trigger an error, as will the usual IO failures (missing permissions, etc.).

But most people would probably use a shell scripting language instead of Python to solve this. For example, here’s something equivalent in Bash (untested):
mkdir segment-{1..8}

for file in *.fa *.fasta; do
    segment=$(sed 's/.*segment \([[:digit:]]\).*/\1/; q' "$file")
    if [[ -n $segment ]]; then
    mv "$file" "segment-$segment"
    done
done

> **Comments:**
> **username_4**: Very cool code.  

---

### Answer by username_2 on 2020-10-30. Score: 1

One "out there" approach you could take is to create a fasta file containing your regions of interest (as separate sequences), and then map your fasta files to that reference fasta file, generating BAM/SAM output. After that, position-sort the BAM file, and you've now got a content-sorted list of sequences.
The process to do this would be something like this:
minimap2 -a regions.fasta input1.fasta input2.fasta ... | samtools sort > mapped.bam
samtools fastq mapped.bam > sorted.fasta


---

