Count number of reads in a SAM/ BAM file

  1. Assuming each read consists of four lines:
    my.sam | wc -l
    
    Divide by four Note be aware of headers!
    samtools view my.bam | wc -l
    
    Divide by four, e.g. echo $((`samtools view my.bam | wc -l` / 4))
  2. Using samtools and awk:
    samtools idxstats my.bam | awk '{c+=$3+$4} END {print c}'
    

get number of mapped/ unmapped reads per chromosome

Required: indexed bam file. See here and here.
$ samtools idxstats file.bam
chr1	249250621	5660739	0
chr10	135534747	1598658	0
chr11	135006516	3973679	0
chr12	133851895	3609156	0
chr13	115169878	372222	0
chr14	107349540	1575999	0
chr15	102531392	1640999	0
chr16	90354753	4815880	0
chr17	81195210	4425034	0
chr18	78077248	296313	0
chr19	59128983	5379034	0
chr2	243199373	2873720	0
chr20	63025520	2503494	0
chr21	48129895	1282107	0
chr22	51304566	1689558	0
chr3	198022430	2266705	0
chr4	191154276	975412	0
chr5	180915260	1975905	0
chr6	171115067	2465368	0
chr7	159138663	3807487	0
chr8	146364022	2124000	0
chr9	141213431	2403650	0
chrM	16571		1000869	0
chrX	155270560	1866583	0
chrY	59373566	126893	0
From the manual:
samtools idxstats in.sam|in.bam|in.cram

Retrieve and print stats in the index file corresponding to the input file. Before calling idxstats, the input BAM file must be indexed by samtools index.

The output is TAB-delimited with each line consisting of reference sequence name, sequence length, # mapped reads and # unmapped reads. It is written to stdout.