Tools‎ > ‎

SAMtools

Download and install

wget https://github.com/samtools/samtools/releases/download/1.3.1/samtools-1.3.1.tar.bz2
tar -jvxf samtools-1.3.1.tar.bz2
cd samtools-1.3.1
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

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

Stats

get number of alignments
samtools view -c SAMPLE.bam

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