Using Samtools On Many Files Recursively In One Go
1
0
Entering edit mode
11.9 years ago
Vikas Bansal ★ 2.4k

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 • 13k views
ADD COMMENT
9
Entering edit mode
11.9 years ago

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

ADD COMMENT
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode

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

ADD REPLY
0
Entering edit mode

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.

ADD REPLY

Login before adding your answer.

Traffic: 2433 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6