the thing is I have hundreds of sam in the folder. it will take forever to do this one after the other to generate all bams before I merge them
Hello everyone, I have a folder that contains among other files, a list of sam files that was split previously by someone else. I want to use the same file but in the un-split form so I am looking for a way to:
- separate them out of the folder using grep because they are many (what grep command please?)
- Merge them into one Sam file.
Thanks
2 answers
From sam to sorted bam:
for f in *.sam; do filename="${f%%.*}"; samtools view -bS $f | samtools sort -@ 4 - ${filename}.sorted.bam; done
Then you can merge them:
samtools merge out.bam in1.bam in2.bam in3.bam
So you can use:
samtools merge out.bam `ls *sorted.bam`
Source: http://www.htslib.org/doc/samtools.html
Note:
-@ for number of threads.
Instead of for loop you can use parallel; refer to this example:
A: Run Samtools on multiple files
Then use parallel as suggested above
If you want use sam directly use MergeSamFiles from Picard tools:
java -jar picard.jar MergeSamFiles \
I=input_1.bam \
I=input_2.bam \
O=output_merged_files.bam
https://software.broadinstitute.org/gatk/documentation/tooldocs/4.0.0.0/picard_sam_MergeSamFiles.php
cat sample1.sam sample2.sam sample3.sam > merged.sam
That won't work because of headers.
Thanks for the fast response. So my folder looks like this
> xx.sam
> 18.txt
> 19.txt
> 20.txt
xy.sam
18xy.txt
19xy.txt
20xy.txt
xz.sam
18xz.txt
19xz.txt
20xz.txt
and the file continues in this format....
I just need to get out the sam files out of the folder so I can perform the merg.
Thanks again
Log in to answer this question.