This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Extract Line By Line In *.Bam Files

Hello!

I'm working with a .bam file and I want extract line by line. I'm trying to use the following bash command:

for line in `samtools view filename.bam`
do
     something
done

but it doesn't works because the variable line will be a single field of .bam file. How can I assign at variable the entire line?

Thanks!

bam samtools

2 answers

Try something like

samtools view file | while read LINE; do echo $LINE; done

(edit: a little warning here: this is untested, I don't have samtools)

This would be my solution too, assuming that "samtools view" outputs a multi-line file.

Do you mean multi-line stdout? A file would need to be handled with cat file | ..

yeah, I meant stdout :-)

I agree with Michael that you can just pipe the output, depending what you want to do determines if you need the while loop or not.

You can just pipe the output into another tool, such as perl.

This example randomly samples the BAM file to give an output BAM file with half as many reads.

samtools view -h input.bam | perl -ne 'if (m/^@[HD|SQ|RG|PG|CO]/){print;next};
srand;print if rand() <=0.5' | samtools view -Sb - >output.bam

Here is another example that counts the number of reads on each chromosome

samtools view input.bam | cut -f 3 | sort |uniq -c

Log in to answer this question.