This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Using Samtools On Many Files Recursively In One Go

Hi,

I have around 30 sam files in my different directories -

 ./sff*/mapping/out.sam

So in my current directory there are around 30 directories naming sff41, sff42,...,sff71,etc and then in each directory there is sub-dir called mapping in which I have out.sam files. Now I want to-

  1. Convert file from SAM to BAM format

  2. Sort BAM file

  3. index the bam file

One option is to do it 1 by 1 which is very annoying. I also found something on this blog but it assumes all sam files with different names in one directory. I am pasting bash script from this blog-

for sample in *.sam  
 do  
   echo $sample  
   describer=$(echo ${sample} | sed 's/.sam//')  
   echo $describer  

   # Convert file from SAM to BAM format  
   samtools view -b $sample > ${describer}.uns.bam  

   # Sort BAM file  
   samtools sort ${describer}.uns.bam ${describer}   

   # index the bam file  
   samtools index ${describer}.bam  

   # Revove intermediate files  
   rm ${describer}.uns.bam  
 done

Can anyone please suggest how to modify this according to my directories or if you have any other fast method to achieve this?

Thanks in advance.

samtools linux

1 answer

Hey, I think this should do

for i in sff*/mapping/*out.sam; do samtools view -bS $i | samtools sort - $i.sorted && echo $i "bam sorted" && samtools index $i.sorted.bam; done

Cheers

Thanks. Just 1 correction, in "samtools index $i.sorted" it should be "samtools index $i.sorted.bam" with.bam in the end.

Yeah, sorry I didn't tested the indexing part. Cheers

The original code is right and there is no need to add ".bam" to "samtools index $i.sorted.bam", since the output of previous command "samtools sort - $i.sorted" generates a file named "$i.sorted" which is consequently piped into next commands.

Log in to answer this question.