This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Merge multiple Sam files to one big Sam file. How?

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:

  1. separate them out of the folder using grep because they are many (what grep command please?)
  2. Merge them into one Sam file.

Thanks

sam samtools overlapzscore heatmap

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

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

That's what screen or tmux are for. Coupled with parallel that should do the trick.

Im not an expert in this field, so some of the terms are strange to me. However, I will try to install picard and try the command. Thanks

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.