<p>I'd use GNU parallel. I've not tested this with real files but try it out, ensure the <code>{}</code> is passed to the process substitution:</p>
<pre><code>mkdir with_header
parallel samtools view -b &lt;(cat my_header {}) -o with_header/{} ::: *.bam
</code></pre>
<p>The command could be better - out file name could be done better but you get the concept.</p>

CC BY-SA 4.0
2023-07-13T14:20:40.307Z
2023-07-13T14:20:40.307Z
Ram RS
<p>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?</p>
<p>One solution is to create intermediate files:</p>
<pre><code>for samfile in *.sam
do
  cat my_header &gt; tmp.sam
  cat $samfile &gt;&gt; tmp.sam
  samtools view -b tmp.sam &gt; $samfile.bam
done
</code></pre>
<p>But that seems inelegant and I feel like I'm missing the better way.</p>

<samtools><bash>
Create bam from separate sam and header
# Create bam from separate sam and header

(Asked by: username_0 on 2023-07-12)

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
do
  cat my_header > tmp.sam
  cat $samfile >> tmp.sam
  samtools view -b tmp.sam > $samfile.bam
done

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

**Tags:** samtools, bash

---

## 1 answers

### Answer by username_1 on 2023-07-13. Score: 1 | Accepted answer

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.


---

