Compress and index a VCF with bgzip and tabix
Block-compress a VCF with bgzip and build a tabix index so you can pull variants from any genomic region in milliseconds.
Prerequisites
- htslib installed (`bgzip`, `tabix`)
- A VCF file with records sorted by chromosome and position
1Block-compress the VCF
bgzip compresses the VCF in place, replacing calls.vcf with calls.vcf.gz. Unlike plain gzip, the BGZF format writes independent compressed blocks that tabix can seek into. The command prints nothing on success.
bgzip calls.vcfExpected output
# bgzip prints nothing on success
# calls.vcf is replaced by calls.vcf.gz2Build the tabix index
Index the compressed file with the VCF preset. This is also silent and writes calls.vcf.gz.tbi next to your data. The index maps genomic coordinates to byte offsets inside the BGZF blocks.
tabix -p vcf calls.vcf.gzExpected output
# tabix prints nothing on success
# creates the index calls.vcf.gz.tbi3Query a genomic region
Ask for any region as chrom:start-end. Tabix seeks straight to the matching blocks and streams the overlapping records instead of scanning the whole file. Add -h if you also want the VCF header lines prepended.
tabix calls.vcf.gz chr1:1000000-2000000Expected output
chr1 1000920 rs6054257 G A 29.0 PASS NS=3;DP=14;AF=0.5 GT:GQ:DP 0|1:48:8
chr1 1234567 . T C 52.0 PASS NS=3;DP=22;AF=0.33 GT:GQ:DP 1|0:45:12
chr1 1876543 rs62636508 C G 41.0 PASS NS=2;DP=18;AF=0.25 GT:GQ:DP 0|0:39:10Troubleshooting
[tabix] the file out of order at line ...
The VCF must be position-sorted before indexing. Sort and compress in one pass with `bcftools sort calls.vcf -Oz -o calls.sorted.vcf.gz`, then run `tabix -p vcf calls.sorted.vcf.gz`.
"not a BGZF file" or tabix fails to index
The file was compressed with plain gzip, not bgzip. Decompress it with `gunzip calls.vcf.gz` and re-run `bgzip calls.vcf`.