Download and install


tar -jvxf samtools-1.11.tar.bz2

cd samtools-1.11


make prefix=$HOME/tools/samtools install   # path where to install samtools

# add path to your .bashrc file

export PATH=$HOME/tools/samtools/bin/:$PATH


convert a SAM file to a BAM file

samtools view -b -S SAMPLE.sam > SAMPLE.bam

  -S Input is in SAM format

  -b Output in BAM format

convert a BAM file to a SAM file

samtools view -h SAMPLE.bam > SAMPLE.sam

sort a BAM file

samtools sort SAMPLE.bam -o SAMPLE_sorted.bam

# using a unix pipe (input '-')

cat SAMPLE.bam | samtools sort - -o SAMPLE_sorted.bam

samtools sort SAMPLE.bam SAMPLE   # old version v1.2

sort by readName

samtools sort -n SAMPLE.bam -o SAMPLE_sorted.bam


get number of reads

get number of individual reads, paired reads that mapped both count double R1+R2

samtools view -c SAMPLE.bam

→ How to count the number of mapped reads in a BAM or SAM file (SAM bitcode fields)

more statistics about alignments

samtools flagstat SAMPLE.bam

comprehensive statistics

samtools stats SAMPLE.bam

Get coverage

# get coverage of a selected region (e.g., from base 1,958,700 to 1,958,907 of a contig)

samtools index sampleID.bam

samtools mpileup -r 'contigName:1,958,700-1,958,907' sampleID.bam

# same in combination with awk to count the total and averaged coverage

samtools mpileup -r 'contigName:1,958,700-1,958,907' sampleID.bam | awk 'BEGIN{C=0}; {C=C+$4}; END{print C "\t" C/NR}'

see also: → Calling SNPs/INDELs with SAMtools/BCFtools

Note: SAMtools mpileup counts only primary aligned reads. SAMtools discards unmapped reads, secondary alignments and duplicates. To consider also secondary alignments, BEDtools could be an alternative.

SAMtools documentation

Samtools homepage

Samtools documentation

Introduction by Dave Tang

Alternative BAM processing tools

→ Sambamba

→ BEDtools