This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Separating mapped and unmapped reads from BAM file

Dear all,

I am trying to separate mapped and unmapped reads from a BAM file following these instructions. But when I run

$ samtools sort <unsorted>.bam -o <file>.bam
$ samtools view -F 4 <file>.bam > <file>_mapped.bam

then I get

$ samtools view -H <file>_mapped.bam
$ samtools view -c <file>_mapped.bam 
[E::sam_parse1] missing SAM header
[W::sam_read1] Parse error at line 1
[main_samview] truncated file.

If I include the header, I get

$ samtools view -H -F 4 <file>.bam > <file>_mapped.bam
$ samtools view -H <file>_mapped.bam
@HD VN:1.3  SO:coordinate
@SQ SN:21   LN:46709983
@PG ID:bwa  PN:bwa  VN:0.7.17-r1188 CL:bwa mem -t 10 ./ref/GRCh38-21.fa 501N-1_1.fq.gz 501N-1_2.fq.gz -o aln/501N_bwa.sam
$ samtools view -c <file>_mapped.bam 
0

But the starting file has more than 0 mapped reads

$ samtools view -c -F 4 <file>.bam 
116519052

What am I getting wrong?

Thank you

sequencing sequence assembly

1 answer

Hello marongiu.luigi,

$ samtools view -H -F 4 <file>.bam > <file>_mapped.bam

The upper case -H is wrong. It must be -h.

-h        Include the header in the output. 
-H        Output the header only.

Or you take -b as you like to have a bam file as output.

$ samtools view -b -F 4 <file>.bam > <file>_mapped.bam

You can also define the output name using -o. samtools than recognize the file extension and in case it is bam it includes the header automaticly.

$ samtools view -F 4 <file>.bam -o <file>_mapped.bam

fin swimmer

Log in to answer this question.