This is a test version of Biostars. For the public version, visit https://www.biostars.org.
sam.gz files to bam using samtools

Hello bioinformaticians,

I wish to convert compressed aligned.sam.gz files to aligned.bam files using samtools. Is it possible?

I tried this command

samtools sort -@ 8 -o aligned.bam aligned.sam.gz

Suggestions are welcome

rna-seq samtools

2 answers

Try the following in bash:

zcat aligned.sam.gz | samtools view -o aligned.bam

To sort, do the following:

zcat aligned.sam.gz | samtools sort -o aligned.bam

The -@ 8 (multi-threading) is optional

gzip -cd is more generic that zcat as macOS zcat behaves differently than Linux zcat.

You command is perfectly fine, assuming you actually meant "sort", given your request was "convert". If you really just meant convert then use "view" instead.

You said you tried the command, but didn't give us anything else to go on. I assume it didn't work, or you wouldn't be here, but maybe an error message would help get sensible replies? Also which version of samtools are you using? Please use the latest versions where possible.

Note there may be a difference in performance between gzipped SAM and bgzfed SAM. They're both gz format, but bgzf is random access so the decode can be parellelised in addition to the encode side.

Finally, this sort of implies you're running an aligner | gzip > sam.gz and then want to sort and convert to bam. If so, why? It's better to just pipe the output of the aligner directly into the next part of the pipeline (eg markdup if doing that, or skip that and samtools sort). Samtools can read from stdin and it'll auto-detect the file format too.

Log in to answer this question.