If I have multiple SAM files without header, and a header saved in a separate file, how do I convert that to a BAM file?

One solution is to create intermediate files:

for samfile in *.sam
  cat my_header > tmp.sam
  cat $samfile >> tmp.sam
  samtools view -b tmp.sam > $samfile.bam

But that seems inelegant and I feel like I'm missing the better way.


1 Answer 1


I'd use GNU parallel. I've not tested this with real files but try it out, ensure the {} is passed to the process substitution:

mkdir with_header
parallel samtools view -b <(cat my_header {}) -o with_header/{} ::: *.bam

The command could be better - out file name could be done better but you get the concept.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.