# How to Convert SAM to FASTA: Reconstructing Reads from Alignment Files

By the end of this guide you will be able to take a SAM, BAM, or CRAM alignment file and produce a FASTA file of reads, either as one combined file or split into READ1, READ2, singleton, and unassigned files. You will know which command-line options control filtering, how to verify that the output is complete, and which parts of the original read survive the conversion and which are gone for good.

You need a Unix-like shell, a recent samtools installation, and the alignment file. Optional tools that make the job easier are seqtk, seqkit, and bedtools. No reference genome is needed for BAM or SAM input. CRAM input may need the reference unless the reference is embedded in the file.

## What SAM, BAM, CRAM, FASTA, and FASTQ Actually Store

The first step in any conversion is knowing what each format contains. Interoperability between formats is a recurring source of practical difficulty because each format was designed for a different job and stores a different subset of the data [1].

### SAM is an alignment format, not a read archive

SAM stands for Sequence Alignment/Map. It is a tab-delimited text format with one line per alignment record and an optional header block at the top. The header carries reference names and lengths (`@SQ`), read groups (`@RG`), and the program chain (`@PG`). Every alignment record has 11 mandatory fields, in this order:

| Field | Name | What it holds |
|--|--|--|
| 1 | QNAME | read name |
| 2 | FLAG | bitwise status code |
| 3 | RNAME | reference name |
| 4 | POS | 1-based leftmost mapping position |
| 5 | MAPQ | mapping quality |
| 6 | CIGAR | alignment operations |
| 7 | RNEXT | reference name of the mate |
| 8 | PNEXT | position of the mate |
| 9 | TLEN | observed template length |
| 10 | SEQ | read sequence |
| 11 | QUAL | base qualities in Phred+33 ASCII |

The FLAG field packs several independent booleans into one integer. These bits matter for filtering during conversion.

| Bit | Hex | Meaning |
|--|--|--|
| 1 | 0x1 | template has multiple segments (paired) |
| 2 | 0x2 | each segment properly aligned |
| 4 | 0x4 | segment unmapped |
| 8 | 0x8 | mate unmapped |
| 16 | 0x10 | SEQ is reverse complemented |
| 32 | 0x20 | mate is reverse complemented |
| 64 | 0x40 | first segment in template |
| 128 | 0x80 | last segment in template |
| 256 | 0x100 | secondary alignment |
| 512 | 0x200 | not passing QC |
| 1024 | 0x400 | duplicate |
| 2048 | 0x800 | supplementary alignment |

The CIGAR string describes how the read relates to the reference. `M` is an alignment match, `I` is an insertion to the reference, `D` is a deletion, `S` is a soft clip (bases present in SEQ but not aligned), and `H` is a hard clip (bases removed from SEQ entirely). Soft-clipped bases are recoverable. Hard-clipped bases are not.

### BAM and CRAM are compressed SAM

BAM is the binary, block-compressed form of SAM. It stores the same fields and is usually 5 to 10 times smaller than the text file for the same content. CRAM is a reference-based compression format that stores only the differences between reads and a reference, so it is smaller still and depends on the reference sequence for decoding. Both formats are read and written by HTSlib, which samtools uses internally.

### FASTA stores sequence only

FASTA is the simplest sequence format. Each record starts with a header line that begins with `>` followed by an identifier and an optional description. Sequence lines follow until the next header. There is no quality information and no alignment information. A FASTA record is just a name and a string of letters.

```
>readA/1
ACGTACGTACGTACGTACGT
```

### FASTQ stores sequence plus base qualities

FASTQ adds a quality string. Each record has four lines: an `@` header, the sequence, a `+` separator, and one ASCII character per base. The characters encode Phred quality scores using an offset of 33 in modern files. A Phred score of 20 is the character `5` (ASCII 53), and a Phred score of 30 is the character `?` (ASCII 63). Quality values are what allow variant callers, trimmers, and error correctors to weigh one base against another.

### FASTQ vs FASTA: the difference that matters

| Feature | FASTA | FASTQ |
|--|--|--|
| Header marker | `>` | `@` |
| Sequence | yes | yes |
| Base qualities | no | yes |
| Typical use | similarity search, assembly, multiple alignment, primer design | variant calling, trimming, error correction, re-alignment |
| Size per read | smaller | roughly 2x the sequence length |
| Recoverable from BAM | yes, if SEQ is present | yes, if SEQ and QUAL are present |

The choice between FASTA and FASTQ is really a choice about whether downstream software needs base-level confidence. Dropping quality scores is a lossy operation, and format designers often build new formats specifically to avoid losing information that later analysis might need [2]. Once you write FASTA, the quality string is gone unless you still have the original FASTQ or the BAM it came from.

## Why Convert SAM to FASTA

There are several legitimate reasons to pull reads back out of an alignment file.

- **Similarity search.** You want to BLAST the reads, or search them against a [protein database](/blog/guides/protein-database), and BLASTn or DIAMOND takes FASTA.
- **Reassembly.** You want to re-assemble reads with a different assembler, often after filtering to unmapped or soft-clipped reads.
- **Multiple alignment.** You want to align a set of reads to each other, not to a reference, to look at a repeat or a paralog.
- **Primer and probe design.** You want the actual read sequences in a region, free of alignment gaps and reference bias.
- **Contamination checks.** You want to screen reads against a panel of common vectors or host sequences.
- **Sharing and archiving.** FASTA is smaller and easier to inspect than BAM, and many public sequence databases accept FASTA directly [3].
- **Spot checks.** You want to confirm that a BAM contains the reads you think it does.

Conversion is less appropriate when you need base qualities, when you need the alignment itself, or when the BAM has been through a pipeline that removed or altered the original sequences.

## What You Need Before You Start

Install samtools and confirm the version. Any version from 1.16 onward supports the options used here, and older versions mostly work with the same syntax.

```
samtools --version
```

Expected output looks like this:

```
samtools 1.19
Using htslib 1.19
Copyright (C) 2023 [Genome Research](/blog/guides/genome-research) Ltd.
```

Install seqtk and seqkit if you want convenient FASTA formatting and statistics:

```
conda install -c bioconda samtools seqtk seqkit
```

Command-line converters are commonly packaged as Conda packages and containers so that the same command runs on a laptop, a cluster, and a cloud instance [4]. If you work across those environments, pin the container image or the Conda environment file alongside your analysis.

You also need disk space. A human whole-genome BAM at 30x is often 80 to 100 GB, and the FASTA of all reads is roughly the sum of read lengths plus header bytes. Estimate the FASTA size as the number of reads multiplied by the read length, then add about 5 to 10 percent. Check free space before you start.

```
df -h .
```

## How to Convert SAM to FASTA Step by Step

The walkthrough below starts from a SAM file and ends with a verified FASTA plus a short record of how it was made. Each step is independent, so you can skip the BAM conversion if you only need a one-time conversion from a small SAM.

### Step 1: Identify the file type

Do not trust the extension. Use htsfile or samtools to confirm what you actually have.

```
htsfile reads.sam
```

Expected output:

```
reads.sam:     SAM v1 text
```

A BAM reports `BAM version 1` and a CRAM reports `CRAM version 3.0`. If htsfile is not installed, `samtools view -H reads.sam | head` will fail in a characteristic way on a binary file.

### Step 2: Force a full parse of the SAM

Counting the records forces samtools to read every line and will surface malformed records before you build anything on top of them.

```
samtools view -c reads.sam
```

Expected output is a single integer, for example:

```
1487233
```

If the file has a broken record, samtools stops and prints a parse error naming the field. Fix the SAM at the source rather than trying to patch it downstream.

### Step 3: Convert to BAM, sort, and index

You can run `samtools fasta` directly on SAM. Converting to BAM first is worth the extra minute because it compresses the file, lets you run QC commands that expect an index, and gives you a stable input for repeated conversions.

```
samtools view -@ 4 -b -o reads.bam reads.sam
samtools sort -@ 4 -m 2G -o reads.sorted.bam reads.bam
samtools index -@ 4 reads.sorted.bam
samtools quickcheck -v reads.sorted.bam && echo "BAM is intact"
```

The `-@ 4` tells samtools to use four threads. The `-m 2G` gives each sorting thread up to 2 GB of memory before spilling to disk. Successful commands print nothing. The final line prints `BAM is intact` if the file has a valid header and end-of-file marker.

You can also do the conversion and sort in one pipe, which avoids writing the intermediate BAM:

```
samtools view -@ 4 -b reads.sam | samtools sort -@ 4 -m 2G -o reads.sorted.bam -
```

### Step 4: Run samtools fasta

This is the core command. It reads the alignment file, restores each read to its original orientation, and writes FASTA to standard output.

```
samtools fasta reads.sorted.bam > reads.fa
```

The command prints nothing to the terminal. Check that the file is not empty:

```
ls -lh reads.fa
wc -l reads.fa
```

A valid FASTA has at least two lines per record (a header and at least one sequence line), so `wc -l` should be at least twice the number of reads.

### Step 5: Choose filters deliberately

`samtools fasta` applies a default filter that excludes secondary and supplementary alignments. That default is almost always correct, because secondary and supplementary records duplicate sequence that is already present in the primary record. If you disable the filter, you will get duplicate sequences in the FASTA.

The two filtering options are `-f INT` (include reads with any of the listed FLAG bits set) and `-F INT` (exclude reads with any of the listed FLAG bits set). The default is `-F 0x900`, which removes secondary (0x100) and supplementary (0x800) records.

| Goal | Command | Notes |
|--|--|--|
| All primary reads, combined | `samtools fasta reads.sorted.bam > reads.fa` | includes unmapped reads |
| Only unmapped reads | `samtools fasta -f 0x4 reads.sorted.bam > unmapped.fa` | useful for salvage assembly |
| Mapped primary reads only | `samtools fasta -F 0x904 reads.sorted.bam > mapped.fa` | adds unmapped (0x4) to the exclusion |
| Only properly paired reads | `samtools fasta -f 0x2 reads.sorted.bam > proper.fa` | both mates must be mapped |
| Duplicates included | `samtools fasta -F 0x900 reads.sorted.bam` | duplicates are not excluded by default |
| Duplicates removed | `samtools fasta -F 0xD00 reads.sorted.bam` | adds duplicate (0x400) |

The hex arithmetic is worth checking twice. `0x900` is 2304, which is 256 + 2048, so it covers secondary plus supplementary. `0x904` is 2308, which adds unmapped. `0xD00` is 3328, which is 256 + 1024 + 2048, so it covers secondary, duplicate, and supplementary.

### Step 6: Split paired reads into separate files

A single combined FASTA loses the pairing relationship unless the read names carry a `/1` and `/2` suffix or an Illumina suffix. Use `-1`, `-2`, `-0`, and `-s` to write separate files.

```
samtools fasta \
  -1 reads_R1.fa \
  -2 reads_R2.fa \
  -0 reads_unassigned.fa \
  -s reads_singletons.fa \
  reads.sorted.bam > /dev/null
```

- `-1 FILE` receives reads with the first-in-pair flag (0x40).
- `-2 FILE` receives reads with the second-in-pair flag (0x80).
- `-s FILE` receives reads that are paired but whose mate is missing from the file or is unmapped in a way that leaves them without a partner.
- `-0 FILE` receives reads that are not part of a pair at all, including unpaired and single-end reads.
- The trailing `> /dev/null` discards anything that samtools would otherwise send to standard output.

Pairing is assigned by FLAG, not by adjacency in the file. Coordinate-sorted BAM works fine. You do not need to name-sort or collate first.

### Step 7: Control read names

By default samtools appends `/1` or `/2` to paired read names. Use `-n` to keep the names exactly as they appear in the BAM. Use `-N` to force the suffix even when a suffix is already present. Use `-i` to add the Illumina Casava 1.8 suffix (` 1:N:0:INDEX`).

```
samtools fasta -n reads.sorted.bam > reads_noname.fa
samtools fasta -i reads.sorted.bam > reads_casava.fa
```

The `-n` option is convenient when your read names already end in `/1` and `/2`, because it prevents a double suffix such as `readA/1/1`. It is dangerous when the names carry no suffix at all, because the two mates of a pair then become indistinguishable by name. Names are the only link between paired FASTA records once the files are separated.

### Step 8: Inspect the output

Look at the first few records and confirm they look like reads, not like headers or empty lines.

```
head -n 6 reads.fa
```

Expected output resembles:

```
>SRR1234567.1.1 1:N:0:ATCACG
NTTACGGTAACGT...
>SRR1234567.1.2 1:N:0:ATCACG
GCTAGCTAGCTA...
```

Count the records:

```
grep -c '^>' reads.fa
```

The count should match the number of primary records in the BAM.

### Step 9: Verify record counts and total bases

Two checks catch almost every conversion error. First, compare the FASTA record count with the number of primary records in the BAM.

```
grep -c '^>' reads.fa
samtools view -c -F 0x900 reads.sorted.bam
```

The two numbers must be identical. If the FASTA count is lower, reads were dropped. If it is higher, you probably disabled the default filter or ran the command twice into the same file.

Second, compare the total number of bases. Sum the sequence lengths in the FASTA and the SEQ lengths in the BAM.

```
awk '/^>/{if(n){s+=n} n=0; next}{n+=length($0)} END{s+=n; print s}' reads.fa
samtools view -F 0x900 reads.sorted.bam | awk '{s+=length($10)} END{print s}'
```

The two sums must match. If they do not, the most likely cause is a hard-clipped alignment, because the FATSA cannot contain bases that were removed from SEQ. The second most likely cause is a malformed SAM record where SEQ length and CIGAR length disagree.

### Step 10: Normalize line wrapping and clean up

Most FASTA parsers ignore line breaks, but some old tools assume 60 or 70 characters per line. seqtk can rewrap the file without touching the sequence.

```
seqtk seq -l 60 reads.fa > reads.wrapped.fa
```

If you need to strip descriptions and keep only the first token of each header, use a careful substitution. Make sure the resulting names are still unique.

```
sed 's/^>\([^ ]*\).*/>\1/' reads.fa > reads.clean.fa
grep '^>' reads.clean.fa | sort | uniq -d | head
```

An empty output from the last command means no duplicate names. A non-empty output means the cleanup created collisions, usually by stripping `/1` and `/2` from paired reads.

### Step 11: Record provenance

A conversion is an analysis step and should be logged. Save the tool version, the input checksum, and the output checksum next to the FASTA.

```
samtools --version > conversion.log
md5sum reads.sorted.bam reads.fa >> conversion.log
```

Workflow systems that keep an audit trail for every output file make this automatic [5]. If you are not using one, a plain log file is enough to answer the question of which BAM and which samtools version produced a given FASTA six months from now.

## A Worked Example with a Three-Read SAM

A tiny SAM makes the behavior concrete. The fields below are separated by spaces for readability. A real SAM uses tab characters.

```
@HD	VN:1.6	SO:unsorted
@SQ	SN:chr1	LN:1000
readA	99	chr1	100	60	10M	=	200	110	ACGTACGTAC	IIIIIIIIII
readA	147	chr1	200	60	10M	=	100	-110	TGCATGCATG	IIIIIIIIII
readB	0	chr1	300	60	5S5M	*	0	0	TTTTTACGTAC	IIIIIIIIII
readC	4	*	0	0	*	*	0	0	GGGGCCCCAA	IIIIIIIIII
```

Run the basic conversion:

```
samtools fasta small.sam
```

Expected output:

```
>readA/1
ACGTACGTAC
>readA/2
CATGCATGCA
>readB
TTTTTACGTAC
>readC
GGGGCCCCAA
```

Three things happened that are easy to miss. The second readA record has FLAG 147, which includes 0x10, so samtools reverse-complemented the stored `TGCATGCATG` back to `CATGCATGCA`. The readB record has a `5S5M` CIGAR, and the five soft-clipped bases (`TTTTT`) are retained in the output. The readC record is unmapped and still appears, because the default filter does not remove unmapped reads.

Now split the pairs:

```
samtools fasta -1 R1.fa -2 R2.fa -0 other.fa small.sam > /dev/null
```

`R1.fa` contains `readA/1`, `R2.fa` contains `readA/2`, and `other.fa` contains the unpaired `readB` and `readC` records.

Finally, suppress the suffixes:

```
samtools fasta -n small.sam
```

Expected output:

```
>readA
ACGTACGTAC
>readA
CATGCATGCA
>readB
TTTTTACGTAC
>readC
GGGGCCCCAA
```

The two `readA` records now share a name. That is fine for a combined file read by a tool that does not care about names, and it is a problem for any tool that builds a dictionary keyed on the identifier.

## Common Mistakes and Limitations

### Using awk on the SAM text and ignoring read orientation

The tempting one-liner is:

```
samtools view reads.bam | awk 'BEGIN{OFS="\n"} {print ">"$1, $10}' > reads.fa
```

This produces a FASTA-shaped file, but every read with FLAG 0x10 is written in the orientation that aligned to the reference, which is the reverse complement of the original read. It also includes secondary and supplementary records, drops pairing suffixes, and writes a literal `*` for records whose SEQ is missing. Use `samtools fasta` unless you have a specific reason to hand-roll the conversion.

### Expecting hard-clipped bases to come back

Hard clips (`H` in the CIGAR) remove bases from SEQ. No converter can restore them. Some trimming tools hard-clip primers or adapters, and some aligners hard-clip supplementary alignments. If you need the full original read, go back to the FASTQ, not the BAM.

### Looking for quality scores in the output

FASTA has no quality field. If downstream software needs per-base quality, use `samtools fastq` instead. The command syntax and most options are the same, and the output is FASTQ.

```
samtools fastq -1 reads_R1.fq -2 reads_R2.fq reads.sorted.bam > /dev/null
```

### Counting secondary and supplementary alignments twice

The default `-F 0x900` exists for a reason. Setting `-F 0` to "get everything" produces a FASTA in which multi-mapped reads appear several times. That inflates coverage estimates and breaks assemblers that assume each read appears once.

### Filtering out every read

Flag filters combine, and it is easy to write a filter that matches nothing. `-f 0x2 -F 0x4` looks reasonable but excludes unmapped reads while requiring proper pairing, which leaves only a subset. Always run the count check after filtering.

```
samtools fasta -f 0x2 reads.sorted.bam | grep -c '^>'
```

If the answer is zero, the filter is wrong or the BAM has no properly paired reads.

### Treating the BAM as the original read set

A BAM is a record of alignment, not an archive of the sequencing run. Reads may have been trimmed, merged, deduplicated, or filtered before alignment. Overlapping paired reads may have been merged into a single record by the aligner, in which case the two original mates cannot be separated again. Marked duplicates are still present, but they are flagged, not removed. Confirm what the pipeline did before you assume the FASTA represents the original library.

### Creating duplicate names

Removing `/1` and `/2` from paired reads makes the mates share an identifier. Some tools tolerate this and some silently keep only one record. If you need to strip descriptions, keep the mate suffix.

### Forgetting that `=` can appear in SEQ

The SAM specification allows `=` in SEQ to mean "same as the reference base." A few aligners emit this with the `-eqx` option. `samtools fasta` will write the `=` characters literally, and the resulting sequence is not a valid DNA string. Convert with a tool that resolves `=` against the reference, or avoid `-eqx` in the first place.

### Assuming file order equals pairing

Paired reads in a coordinate-sorted BAM are not adjacent. Interleaving them by taking every second record produces nonsense. Use `-1` and `-2` and let samtools assign pairs by FLAG.

### Using FASTA where FASTQ is required

Variant callers, adapters trimmers that use quality, and most error correction tools expect FASTQ. Feeding them FASTA either fails or silently treats every base as high quality. Check the input requirements of the downstream tool before converting.

### Forgetting the CRAM reference

CRAM stores reads as differences from a reference. If the reference is not embedded in the file, samtools needs it to decode the sequences.

```
samtools fasta --reference GRCh38.fa reads.cram > reads.fa
```

Without it, samtools stops with a reference retrieval error. The exact wording depends on the HTSlib version, and it usually names the missing reference sequence identifier.

### Name collisions when merging samples

If you convert several BAMs and concatenate the FASTA files, read names may collide across samples. Prefix each sample before merging, or keep the files separate and track sample identity in the file name.

### A note on malformed files

A few errors are worth recognizing on sight. A BAM that lacks its end-of-file marker produces `[main_samview] truncated file`, which usually means the download or copy was interrupted. A text SAM passed to a tool that expects BAM produces `[E::bgzf_read_block] Invalid BGZF header at offset 0`. An index that is older than its BAM produces `[E::idx_find_and_load] Could not retrieve index file for 'reads.sorted.bam'`, which is fixed by rerunning `samtools index`. A record whose sequence length does not match its CIGAR produces `[E::sam_parse1] CIGAR and query sequence are of different length`, which means the SAM was generated incorrectly and should be regenerated rather than patched.

### Validate the conversion, do not assume it

Conversion tools can report success while producing an incomplete file. Projects that convert between complex formats routinely measure completeness after the fact rather than trusting the exit code [6]. The same discipline applies here. Count records, sum bases, and spot-check a handful of reads against the original FASTQ if you still have it. Automated round-trip tests between input and output are the standard way to catch mapping errors in format converters [7].

## Frequently Asked Questions

### Can I convert SAM to FASTA without samtools?

Yes, with caveats. A short awk or Python script can read the SEQ field, but it must reverse-complement reads with FLAG 0x10, skip secondary and supplementary records, and handle missing SEQ. Getting those details right is exactly what samtools already does, so a hand-rolled script is only worth writing when samtools is unavailable.

### Does samtools fasta restore the original read orientation?

Yes. Reads flagged 0x10 are reverse-complemented back to the orientation they had in the original FASTQ. A naive field extraction does not do this and will silently produce reverse-complemented sequences for roughly half of a typical Illumina library.

### How do I extract only unmapped reads?

Use `samtools fasta -f 0x4 reads.bam > unmapped.fa`. The `-f` option includes reads with the unmapped bit set. The default exclusion of secondary and supplementary records still applies.

### Why does my FASTA have fewer records than the SAM?

The most common causes are the default filter removing secondary and supplementary records, records with SEQ set to `*` being skipped, or a flag filter that excludes more than intended. Compare `grep -c '^>'` with `samtools view -c -F 0x900` to find the gap.

### Can I get base qualities back after converting to FASTA?

No. FASTA has no quality field, and the information is not stored anywhere in the FASTA file. Re-run the conversion with `samtools fastq` if you still have the BAM, or go back to the original FASTQ.

### How do I split paired reads into two FASTA files?

Use `samtools fasta -1 R1.fa -2 R2.fa -0 other.fa -s single.fa reads.bam > /dev/null`. The `-1` and `-2` files receive first and second mates based on the FLAG field, not on position in the file. Coordinate-sorted BAM works without any pre-sorting.

### Can I convert CRAM directly to FASTA?

Yes. `samtools fasta reads.cram > reads.fa` works when the CRAM contains or can find its reference. Otherwise add `-reference genome.fa`. CRAM conversion is usually slower than BAM conversion because each read must be reconstructed against the reference.

### How do I check that the conversion is complete?

Compare the FASTA record count with `samtools view -c -F 0x900`, and compare the total sequence length in the FASTA with the sum of SEQ lengths from the same filtered BAM records. Both numbers should match exactly. Record the samtools version and the input checksum in a log so the conversion can be reproduced.

<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "FAQPage",
  "mainEntity": [
    {
      "@type": "Question",
      "name": "Can I convert SAM to FASTA without samtools?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Yes, with caveats. A short awk or Python script can read the SEQ field, but it must reverse-complement reads with FLAG 0x10, skip secondary and supplementary records, and handle missing SEQ. Getting those details right is exactly what samtools already does, so a hand-rolled script is only worth writing when samtools is unavailable."
      }
    },
    {
      "@type": "Question",
      "name": "Does samtools fasta restore the original read orientation?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Yes. Reads flagged 0x10 are reverse-complemented back to the orientation they had in the original FASTQ. A naive field extraction does not do this and will silently produce reverse-complemented sequences for roughly half of a typical Illumina library."
      }
    },
    {
      "@type": "Question",
      "name": "How do I extract only unmapped reads?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Use samtools fasta -f 0x4 reads.bam > unmapped.fa. The -f option includes reads with the unmapped bit set. The default exclusion of secondary and supplementary records still applies."
      }
    },
    {
      "@type": "Question",
      "name": "Why does my FASTA have fewer records than the SAM?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "The most common causes are the default filter removing secondary and supplementary records, records with SEQ set to an asterisk being skipped, or a flag filter that excludes more than intended. Compare the FASTA header count with samtools view -c -F 0x900 to find the gap."
      }
    },
    {
      "@type": "Question",
      "name": "Can I get base qualities back after converting to FASTA?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "No. FASTA has no quality field, and the information is not stored anywhere in the FASTA file. Re-run the conversion with samtools fastq if you still have the BAM, or go back to the original FASTQ."
      }
    },
    {
      "@type": "Question",
      "name": "How do I split paired reads into two FASTA files?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Use samtools fasta -1 R1.fa -2 R2.fa -0 other.fa -s single.fa reads.bam. The -1 and -2 files receive first and second mates based on the FLAG field, not on position in the file. Coordinate-sorted BAM works without any pre-sorting."
      }
    },
    {
      "@type": "Question",
      "name": "Can I convert CRAM directly to FASTA?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Yes. samtools fasta reads.cram works when the CRAM contains or can find its reference. Otherwise add, reference genome.fa. CRAM conversion is usually slower than BAM conversion because each read must be reconstructed against the reference."
      }
    },
    {
      "@type": "Question",
      "name": "How do I check that the conversion is complete?",
      "acceptedAnswer": {
        "@type": "Answer",
        "text": "Compare the FASTA record count with samtools view -c -F 0x900, and compare the total sequence length in the FASTA with the sum of SEQ lengths from the same filtered BAM records. Both numbers should match exactly. Record the samtools version and the input checksum in a log so the conversion can be reproduced."
      }
    }
  ]
}
</script>

## Two Short Notes on Tooling and Trust

Format conversion libraries are easiest to maintain when parsing, internal storage, and writing are separate concerns, because each can be tested independently [8]. The same logic applies to command-line work. Keep the conversion step separate from the analysis step, keep the intermediate BAM, and keep a log. When you need to feed the FASTA into a downstream tool that has its own parser, test that parser on a handful of records before running it on millions. Biopython and similar libraries make this easy for FASTA specifically [9].

Bidirectional converters have to map every field in both directions, and proprietary or versioned extensions are where that mapping usually breaks [10]. SAM, BAM, and CRAM share a specification but not identical feature sets, so a conversion that works on one file may hit an edge case on another. The checks in Step 9 are the cheapest way to catch those edge cases before they reach an assembly or a database submission.

## Sources

1. [hictk: blazing fast toolkit to work with .hic and .cool files.](https://pubmed.ncbi.nlm.nih.gov/38913844/)
2. [HXMS: a standardized file format for HX-MS data.](https://pubmed.ncbi.nlm.nih.gov/41803064/)
3. [EMBL2checklists: A Python package to facilitate the user-friendly submission of plant and fungal DNA barcoding sequences to ENA.](https://pubmed.ncbi.nlm.nih.gov/30629718/)
4. [ThermoRawFileParser: Modular, Scalable, and Cross-Platform RAW File Conversion.](https://pubmed.ncbi.nlm.nih.gov/31755270/)
5. [SciPipe: A workflow library for agile development of complex and dynamic bioinformatics pipelines.](https://pubmed.ncbi.nlm.nih.gov/31029061/)
6. [Enhancing semantic interoperability in precision medicine: converting OMOP CDM to Beacon v2 in the Spanish IMPaCT-Data project.](https://pubmed.ncbi.nlm.nih.gov/42420997/)
7. [anndataR improves interoperability between R and Python in single-cell transcriptomics.](https://pubmed.ncbi.nlm.nih.gov/42108549/)
8. [IOData: A python library for reading, writing, and converting computational chemistry file formats and generating input files.](https://pubmed.ncbi.nlm.nih.gov/33368350/)
9. [Fasta2Structure: a user-friendly tool for converting multiple aligned FASTA files to STRUCTURE format.](https://pubmed.ncbi.nlm.nih.gov/38365590/)
10. [cd2sbgnml: bidirectional conversion between CellDesigner and SBGN formats.](https://pubmed.ncbi.nlm.nih.gov/31904823/)