Skip to main content
v2026.11,986 entries · CC-BY 4.0

samtools merge: Combine Sorted BAM Files, Read Groups and Headers

How samtools merge combines sorted BAM files: syntax, sort flags, @RG/@PG handling, worked example and common errors.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

samtools merge combines several sorted alignment files into one sorted output file that keeps every input record and the existing sort order. The basic call is samtools merge -o out.bam in1.bam in2.bam; the options you pass must match how the inputs were sorted, or the output order is undefined. This guide follows the documentation for samtools 1.25 on htslib.org.

What samtools merge is used for in research

A sequencing project often produces one alignment file per lane, per flow cell, per library or per sample batch. Downstream steps usually want one file per biological sample, so the per-lane files are merged after alignment and sorting. The manual describes the command in exactly these terms: it merges multiple sorted files into a single file, producing a single sorted output that contains all the input records and maintains the existing sort order.

Because the command preserves records rather than recomputing them, two questions decide whether a merge is safe: are all inputs sorted the same way, and do their headers describe the same reference sequences and read groups? Most merge problems in practice trace back to one of those two. If you need background on the file formats, see what a BAM file is and the SAM vs BAM vs CRAM comparison; for the flag field that many filters use, see decoding SAM flags.

How to install or access it

samtools is distributed as source from the HTSlib project site. The download page lists samtools, bcftools and htslib as separate packages, each bundling its own copy of htslib so it can be built independently. The current source release listed there is samtools-1.25, and the manual page you are reading about carries the same version, released on 27 October 2026. The documented build is three commands run inside the unpacked source directory:

cd samtools-1.x
./configure --prefix=/where/to/install
make
make install

The programs are installed into a bin subdirectory of the chosen prefix, so you may need to add that directory to your PATH (for example export PATH=/where/to/install/bin:$PATH in sh or bash). On a shared cluster the sensible route is to check whether your site already provides samtools as a module and to confirm its version with your administrators, because option availability depends on the version installed. If you run merges as batch jobs, the sbatch job script guide covers the surrounding scheduler script.

Step-by-step: merge sorted BAM files

1. Confirm every input has the same sort order

The merge command assumes sorted input. Per the manual, the ordering of records in the input files must match the usage of the -n, -N, -t and --template-coordinate options; if they do not, the output order is undefined. The default, with none of these options, is coordinate order. The manual also disallows mixing queryname files that use a combination of natural and lexicographical orders. The data table below lays out which option belongs with which sort order.

2. Choose the output name

There are two documented synopses:

samtools merge [options] -o out.bam [options] in1.bam ... inN.bam
samtools merge [options] out.bam in1.bam ... inN.bam

With -o, every filename argument is an input. Without it, the first non-option filename is taken as the output, so a missing -o turns your first intended input into the output name. There is no default output: to write to standard output or a pipe use -o -, or - as the first filename. -f forces overwriting an output file that already exists, so leave it off until you are sure of the argument order.

3. Run the merge

For coordinate-sorted inputs, the minimal command is:

samtools merge -o merged.bam lane1.bam lane2.bam lane3.bam

If the inputs are listed in a text file, one per line, pass it with -b instead of typing every name. For larger jobs add -@ INT to use extra compression threads (the default is 0 extra threads), -1 for Deflate compression level 1, or -u for uncompressed BAM output when the file will be consumed immediately by another step.

4. Handle read groups and headers deliberately

This is where merges differ from a plain concatenation. Unless -c or -p is given, any @RG or @PG ID that duplicates an existing ID in the output header gets a suffix appended, and the read records are updated to match. The manual’s worked example attaches a read group to each record from its file name:

printf '@RGtID:gatSM:hstLB:gatPL:ILLUMINAn@RGtID:454tSM:hstLB:454tPL:LS454n' > rg.txt
samtools merge -rh rg.txt merged.bam ga.bam 454.bam

Here -r attaches an RG tag to each alignment with the value inferred from the file name, and -h rg.txt supplies the header lines (the manual notes the file is in SAM format and any alignment records it contains are ignored). In the merged file, reads from ga.bam carry RG:Z:ga and reads from 454.bam carry RG:Z:454. Because the tag value comes from the file name, the file names must match the @RG IDs you declared.

5. Index the result

If the output is coordinate sorted, you can index it with samtools index merged.bam. The index documentation says the BAI format handles chromosomes up to 512 Mbp (229 bases) and that you need a CSI index (-c) for reads at larger positions. See BAM index (.bai) files for what the index does. Name-sorted output cannot be indexed this way: the sort documentation states that -n, -N and -t are incompatible with samtools index.

Options reference: what each merge option changes

Option Effect (from the manual)
-o FILE Write merged output to FILE; all other filenames are inputs.
-b FILE List of input BAM files, one per line.
-f Overwrite the output file if present.
-h FILE Copy the @ header lines of FILE (SAM format) to the output instead of lines from the first input.
-r Attach an RG tag to each alignment; value inferred from the file name.
-c When several inputs have @RG headers with the same ID, keep only the first one found.
-p Likewise for @PG IDs: use the first file’s line rather than adding a suffix.
-R STR Merge only the region STR.
-L FILE Merge the regions in a BED file; extends -R and cannot be used together with it.
-X Specify custom index file locations when the data folder has no index; index paths are given as trailing arguments.
--no-PG Do not add a @PG line to the output header.
-1, -u Deflate level 1 compression; uncompressed BAM output.
-@ INT Extra compression threads besides the main thread (default 0).

The sort-order options -n, -N, -t TAG and --template-coordinate are listed in the data table below because their value depends on how the inputs were produced.

Output and how to read it

The result is one alignment file in the order the inputs already had. Three things in the output are worth checking after every merge. First, the header: with -h the @SQ lines of the inputs are merged into your supplied header, otherwise into a composite header built from the input headers. Second, the @RG and @PG records: look for IDs with appended suffixes, which show that two inputs shared an ID and -c or -p was not used. Unless you pass --no-PG, the merge also adds its own @PG line. Third, sort order: if the @SQ order differed between coordinate-sorted inputs (the manual’s example is one file listing a, b, c and another listing b, a, c), the output needs to be re-sorted back into coordinate order, and the manual points to samtools sort for ordering rules.

If you merged to feed a conversion step, the BAM to FASTQ guide covers what happens next.

Troubleshooting

The output order looks wrong

Check that the sort option you passed matches how every input was sorted. A name-sorted input merged without -n or -N, or a mix of natural and lexicographic queryname files, gives undefined order according to the manual.

Duplicate read groups with odd suffixes

This is the documented default. Without -c, all @RG headers appear in the output with random suffixes added to their IDs where needed to tell them apart. The manual adds that combining similar headers is usually the right thing to do when the files being merged originated from the same file, which is the case to use -c for. If the inputs are different libraries that happen to reuse an ID, keep the default so they stay distinguishable.

Too many files, or the job is slow

The manual warns that merging thousands of files can hit the operating system limit on simultaneously open files (see ulimit -n) and cause disk thrashing. The command reads 1 MB at a time from each file, which reduces thrashing but adds to memory use, so account for it when setting memory limits. In extreme cases, merge subsets first and then merge the results.

An input file was overwritten or the output name is wrong

If you forget -o, the first filename is the output. Use the -o form when scripting so that the output position cannot shift.

Index files are not next to the inputs

If the data folder does not contain index files, the manual’s -X option lets you specify custom index locations: samtools merge [options] -X out.bam /data_folder/in1.bam /data_folder/in2.bam /index_folder/index1.bai /index_folder/index2.bai.

Both commands below belong to the same samtools package and are documented on htslib.org. The table separates what each is documented to do.

Command Documented behaviour Use it when
samtools merge Merges sorted files; produces sorted output; merges @SQ, @RG and @PG headers. You need one sorted file from several sorted files, with read-group handling.
samtools cat Concatenates BAM or CRAM files of the same format. The sequence dictionary of each input must be identical (the command does not check this). Header comes from the first file unless -h is given. Output goes to stdout unless -o is used. The inputs already share a dictionary and you want fast joining rather than header merging. The cat manual does not describe sort order, so confirm the order of the result yourself.
samtools sort Sorts a SAM, BAM or CRAM file by coordinate by default, or by name or tag with options; updates the @HD SO tag. You must put one file into a known order before merging, or re-sort a merged file whose @SQ order conflicted.

Frequently asked questions

Does samtools merge require sorted input?

Yes. The manual describes it as merging multiple sorted alignment files, and the output is sorted only if the input order matches the sort options you pass.

Which flag do I use for name-sorted BAM files?

Use -n for natural read-name order, where “a7b” appears before “a12b”, or -N for ASCII lexicographic order, where “x12” comes before “x7”. The manual says -n is not suitable for hexadecimal names and that -N suits names whose digits are zero-padded or hexadecimal.

How do I write the merged file to a pipe?

Use -o -, or put - as the first filename. There is no default output.

How do I merge a very large number of BAM files?

List them in a file and pass it with -b, and if the open-file limit or disk thrashing becomes a problem, merge subsets first and then merge those results.

Can I add a read group while merging?

Yes, with -r (combined with -h to supply the @RG header lines, as in the manual example). The tag value is inferred from each file name.

Can I skip the extra @PG line?

Yes, --no-PG stops the command adding a @PG line to the output header.

Sources

Data: samtools merge sort-order options by input sort order (samtools 1.25)

Maps each input sort order to the samtools merge option that must accompany it, the samtools sort option that produces that order, and whether samtools index can index the result; compiled from the samtools-merge, samtools-sort and samtools-index manual pages.

Period covered: 2026.

samtools merge sort-order options by input sort order (samtools 1.25)
Input sort ordersamtools merge optionsamtools sort option that produces itIndexable with samtools index
Coordinate (default)nonenone (default)Yes
Read name, natural (a7b before a12b)-n-nNo
Read name, lexicographic (x12 before x7)-N-NNo
Tag value, then position-t TAG-t TAGNo
Tag value, then name-t TAG with -n-t TAG with -nNo

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about samtools merge: Combine Sorted BAM Files, Read Groups and Headers

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →