Index a FASTA and extract a region with samtools faidx
Build a .fai index for a FASTA file with samtools faidx, then pull any sub-sequence by chromosome and coordinate.
Prerequisites
- samtools installed (`samtools faidx`)
- A FASTA file (e.g. reference.fasta)
1Index the FASTA
Build the .fai index next to your reference. This writes reference.fasta.fai and prints nothing on success. Each line is tab-separated: sequence name, length, byte offset, bases per line, and line width; run `cut -f1,2 reference.fasta.fai` to read chromosome sizes.
samtools faidx reference.fasta
cut -f1,2 reference.fasta.faiExpected output
chr1 248956422
chr2 242193529
chr3 1982955592Extract a region by coordinate
Pass a `name:start-end` region and faidx prints the header plus the sub-sequence to stdout. The interval is 1-based and inclusive, so chr1:100-200 returns 101 bases. Redirect to a file with `> region.fasta` when you want to keep it.
samtools faidx reference.fasta chr1:100-200 > region.fastaExpected output
>chr1:100-200
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNTroubleshooting
[faidx] Failed to fetch sequence in chr1:100-200
The name before the colon must match the FASTA header exactly, up to the first space. List the valid names with `grep '>' reference.fasta` or read the first column of reference.fasta.fai.
[E::fai_build_core] Different line length in sequence 'chr1' at line 42
faidx requires a uniform line width within each record. Re-wrap the file to a fixed width first: `seqkit seq -w 60 in.fasta > wrapped.fasta`, then index wrapped.fasta.