Download and install

wget https://github.com/samtools/samtools/releases/download/1.11/samtools-1.11.tar.bz2

tar -jvxf samtools-1.11.tar.bz2

cd samtools-1.11

make

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

# add path to your .bashrc file

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

http://www.htslib.org/download/

Examples

convert a SAM file to a BAM file

(BAM files are simply compressed SAM files)

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

(decompress BAM in order to manually inspect the mapping file)

samtools view -h SAMPLE.bam > SAMPLE.sam

sort BAM file by mapped location of the reference sequence

(required for  several follow-up analysis)

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 BAM file by readName

(to have paired reads next to each other)

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

Get number of reads

# get number of mapped reads (paired reads that mapped both count twice 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.

Visualize read mapping of a BAM file

→ Tablet


SAMtools documentation

Samtools homepage

Samtools documentation

Introduction by Dave Tang

Alternative BAM processing tools

→ Sambamba

→ BEDtools