This would be my solution too, assuming that "samtools view" outputs a multi-line file.
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!
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)
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.