samtools-view(1)

🌸 NAME 🌸

<pink>samtools-view(1)</pink> β€” this is the manual page for samtools view, aka the iconic little command that views and converts SAM/BAM/CRAM files. Bestie, it's giving β€œI hold your alignments and I can also change their outfit.” πŸ’…

✨ SYNOPSIS ✨

samtools view [options] in.sam|in.bam|in.cram [region...]

πŸŽ€ DESCRIPTION πŸŽ€

Okay so with no options or regions specified, samtools view prints all alignments in the specified input alignment file (in SAM, BAM, or CRAM format) to standard output in SAM format (with no header). No cap. That's the default vibe.

You may specify one or more space-separated region specifications after the input filename to restrict output to only those alignments which overlap the specified region(s). Use of region specifications requires a coordinate-sorted and indexed input file (in BAM or CRAM format). So like, sort and index first, bestie. 🫢

The -b, -C, -1, -u, -h, -H, and -c options change the output format from the default of headerless SAM, and the -o and -U options set the output file name(s). Outfit change, file destination change, whole little makeover. ✨

The -t and -T options provide additional reference data. One of these two options is required when SAM input does not contain @SQ headers, and the -T option is required whenever writing CRAM output. This is not optional-optional, bestie. 😭

The -L, -M, -N, -r, -R, -n, -d, -D, -s, -q, -l, -m, -f, -F, -G, and --rf options filter the alignments that will be included in the output to only those alignments that match certain criteria. Filtering era. πŸ¦‹

The -p option sets the UNMAP flag on filtered alignments then writes them to the output file.

The -x, -B, --add-flags, and --remove-flags options modify the data which is contained in each alignment. Little alignment glow-up. πŸ’–

The -X option can be used to allow user to specify customized index file location(s) if the data folder does not contain any index file. See EXAMPLES section for sample of usage. Very β€œI know where the index lives” of it. πŸ‘‘

Finally, the -@ option can be used to allocate additional threads to be used for compression, and the -? option requests a long help message. More threads, more help, more main character energy. 🌈

πŸ¦‹ REGIONS πŸ¦‹

Regions can be specified as: RNAME[:STARTPOS[-ENDPOS]] and all position coordinates are 1-based. Don't come at me with 0-based coordinates, okay? 😌

Important note: when multiple regions are given, some alignments may be output multiple times if they overlap more than one of the specified regions. Yes, duplicates can happen. It's not a bug, it's just the region vibe check. πŸ’€

Examples of region specifications:

  • chr1 β€” Output all alignments mapped to the reference sequence named chr1 (i.e. @SQ SN:chr1).
  • chr2:1000000 β€” The region on chr2 beginning at base position 1,000,000 and ending at the end of the chromosome.
  • chr3:1000-2000 β€” The 1001bp region on chr3 beginning at base position 1,000 and ending at base position 2,000 (including both end positions).
  • '*' β€” Output the unmapped reads at the end of the file. (This does not include any unmapped reads placed on a reference sequence alongside their mapped mates.)
  • . β€” Output all alignments. (Mostly unnecessary as not specifying a region at all has the same effect.)

πŸ’… OPTIONS πŸ’…

  • -b, --bam β€” Output in the BAM format. BAM era. 🧚
  • -C, --cram β€” Output in the CRAM format (requires -T). You heard her: -T is required, bestie. πŸ’œ
  • -1, --fast β€” Enable fast compression. This also changes the default output format to BAM, but this can be overridden by the explicit format options or using a filename with a known suffix. Speedy little icon. ⭐
  • -u, --uncompressed β€” Output uncompressed data. This also changes the default output format to BAM, but this can be overridden by the explicit format options or using a filename with a known suffix.

This option saves time spent on compression/decompression and is thus preferred when the output is piped to another samtools command. Pipe it, bestie. 🫢

  • -h, --with-header β€” Include the header in the output. Header stays on. πŸŽ€
  • -H, --header-only β€” Output the header only. Header solo. No alignments invited. πŸ’…
  • --no-header β€” When producing SAM format, output alignment records but not headers. This is the default; the option can be used to reset the effect of -h/-H. So if you turned headers on and need them gone again, this is your reset button. ✨
  • -c, --count β€” Instead of printing the alignments, only count them and print the total number. All filter options, such as -f, -F, and -q, are taken into account. The -p option is ignored in this mode. Counting era, but please note -p gets ignored here. 😭
  • --save-counts FILE β€” Save data on the number of records processed, accepted and rejected by any filter options to FILE. The data is stored in JSON format. The counts only include records that are processed through the filtering options. Any records skipped while iterating over regions will not be included, so the number processed may be less than the total number of records in the file. If used with the --fetch-pairs option, counts will be given for records processed during the second pass over the data. JSON receipts. πŸ”₯
  • -?, --help β€” Output long help and exit immediately. Ask and receive. πŸ‘‘
  • -o FILE, --output FILE β€” Output to FILE [stdout]. Yes, stdout is the default vibe. 🌸
  • -U FILE, --unoutput FILE, --output-unselected FILE β€” Write alignments that are not selected by the various filter options to FILE. When this option is used, all alignments (or all alignments intersecting the regions specified) are written to either the output file or this file, but never both. Pick a lane, alignment. πŸ’€
  • -p, --unmap β€” Set the UNMAP flag on alignments that are not selected by the filter options. These alignments are then written to the normal output. This is not compatible with -U. Not compatible! Do not mix those two, bestie. 🚫
  • -t FILE, --fai-reference FILE β€” A tab-delimited FILE. Each line must contain the reference name in the first column and the length of the reference in the second column, with one line for each distinct reference. Any additional fields beyond the second column are ignored. This file also defines the order of the reference sequences in sorting. If you run: samtools faidx <ref.fa>, the resulting index file <ref.fa>.fai can be used as this FILE. Tab-delimited reference lore. πŸ“š
  • -T FILE, --reference FILE β€” A FASTA format reference FILE, optionally compressed by bgzip and ideally indexed by samtools faidx. If an index is not present one will be generated for you, if the reference file is local.

If the reference file is not local, but is accessed instead via https://, s3:// or other URL, the index file will need to be supplied by the server alongside the reference. It is possible to have the reference and index files in different locations by supplying both to this option separated by the string "##idx##", for example:

-T ftp://x.com/ref.fa##idx##ftp://y.com/index.fa.fai

However, note that only the location of the reference will be stored in the output file header. If this method is used to make CRAM files, the cram reader may not be able to find the index, and may not be able to decode the file unless it can get the references it needs using a different method. So like, heads up. πŸ™ˆ

  • -L FILE, --target-file FILE, --targets-file FILE β€” Only output alignments overlapping the input BED FILE [null]. BED file says β€œthese ones.” πŸŽ€
  • -M, --use-index β€” Use the multi-region iterator on the union of a BED file and command-line region arguments. This avoids re-reading the same regions of files so can sometimes be much faster. Note this also removes duplicate sequences. Without this a sequence that overlaps multiple regions specified on the command line will be reported multiple times. The usage of a BED file is optional and its path has to be preceded by -L option. Faster and duplicate-free, lowkey slay. ⚑
  • --region-file FILE, --regions-file FILE β€” Use an index and multi-region iterator to only output alignments overlapping the input BED FILE. Equivalent to -M -L FILE or --use-index --target-file FILE. Same energy, shorter spelling. ✨
  • -N FILE, --qname-file FILE β€” Output only alignments with read names listed in FILE. If FILE starts with ^ then the operation is negated and only outputs alignment with read groups not listed in FILE. It is not permissible to mix both the filter-in and filter-out style syntax in the same command. Pick one mode, bestie. πŸ¦‹
  • -r STR, --read-group STR β€” Output alignments in read group STR [null]. Note that records with no RG tag will also be output when using this option. This behaviour may change in a future release. Future release warning, iykyk. πŸ‘€
  • -R FILE, --read-group-file FILE β€” Output alignments in read groups listed in FILE [null]. If FILE starts with ^ then the operation is negated and only outputs alignment with read names not listed in FILE. It is not permissible to mix both the filter-in and filter-out style syntax in the same command. Note that records with no RG tag will also be output when using this option. This behaviour may change in a future release. Yes, same heads-up as above. 🫢
  • -n, --exclude-no-read-group β€” Do not output alignments that have no read group. No read group? Not invited. πŸ’…
  • -d STR1[:STR2], --tag STR1[:STR2] β€” Only output alignments with tag STR1 and associated value STR2, which can be a string or an integer [null]. The value can be omitted, in which case only the tag is considered.

Note that this option does not specify a tag type. For example, use -d XX:42 to select alignments with an XX:i:42 field, not -d XX:i:42. Tag type stays unspecified, bestie. Don't add the i in the option. 🚨

  • -D STR:FILE, --tag-file STR:FILE β€” Only output alignments with tag STR and associated values listed in FILE [null]. Tag values from a file, cute. πŸŽ€
  • -q INT, --min-MQ INT β€” Skip alignments with MAPQ smaller than INT [0]. MAPQ gatekeeping, but make it numeric. πŸ”₯
  • -l STR, --library STR β€” Only output alignments in library STR [null]. Library filter says hi. πŸ“š
  • -m INT, --min-qlen INT β€” Only output alignments with number of CIGAR bases consuming query sequence β‰₯ INT [0]. CIGAR length check, periodt. 🧚
  • -e STR, --expr STR β€” Only include alignments that match the filter expression STR. The syntax for these expressions is described in the main samtools(1) man page under the FILTER EXPRESSIONS heading. Go read the main page for the expression syntax, bestie. ✨
  • -f FLAG, --require-flags FLAG β€” Only output alignments with all bits set in FLAG present in the FLAG field. FLAG can be specified in hex by beginning with 0x (i.e. /^0x[0-9A-F]+/), in octal by beginning with 0 (i.e. /^0[0-7]+/), as a decimal number not beginning with '0' or as a comma-separated list of flag names.

For a list of flag names see samtools-flags(1). Flag names have their own man page, iconic. πŸ‘‘

  • -F FLAG, --excl-flags FLAG, --exclude-flags FLAG β€” bestie, this one is the blocker πŸ’… it will not output any alignment that has any bit set in FLAG present in the FLAG field. And how do you write FLAG? So many options, pick your fave: hex by starting with 0x (i.e. /^0x[0-9A-F]+/), octal by starting with 0 (i.e. /^0[0-7]+/), a decimal number that does not begin with '0', or a comma-separated list of flag names. Slay, versatility ✨
  • --rf FLAG, --incl-flags FLAG, --include-flags FLAG β€” the opposite vibe 🫢 only output alignments that have any bit set in FLAG present in the FLAG field. FLAG is written exactly the same way as above: hex starting with 0x (i.e. /^0x[0-9A-F]+/), octal starting with 0 (i.e. /^0[0-7]+/), a decimal number not beginning with '0', or a comma-separated list of flag names.
  • -G FLAG β€” this one's the hater 😀 it will not output alignments where all bits set in INT are present in the FLAG field. It's literally the opposite of -f, so -f12 -G12 is the same as no filtering at all β€” they cancel each other out, iconic. FLAG can be hex starting with 0x (i.e. /^0x[0-9A-F]+/), octal starting with 0 (i.e. /^0[0-7]+/), a decimal number not beginning with '0', or a comma-separated list of flag names.
  • -x STR, --remove-tag STR β€” read tag(s) to exclude from output, and yes it's repeatable [null]. STR can be a single tag or a comma separated list β€” or honestly just repeat the option itself as many times as you want, no judgement πŸ’–

If the list starts with a '^' then it gets negated and treated as a request to remove all tags except those in STR. And the list may be empty, so -x ^ will remove all tags. Chaotic but valid πŸŒ€

Heads up bestie: tags will only be removed from reads that pass filtering. The filtered-out girlies keep everything 😭
  • --keep-tag STR β€” keeps only the tags listed in STR, and it's directly equivalent to --remove-tag ^STR. Specifying an empty list will remove all tags. If both --keep-tag and --remove-tag are specified then --keep-tag has precedence (she wins, periodt πŸ‘‘).
Same warning as before: tags will only be removed from reads that pass filtering.
  • -B, --remove-B β€” collapse the backward CIGAR operation. That's it. That's the whole thing πŸŽ€
  • --add-flags FLAG β€” adds flag(s) to read. FLAG can be hex by beginning with 0x (i.e. /^0x[0-9A-F]+/), octal by beginning with 0 (i.e. /^0[0-7]+/), a decimal number not beginning with '0', or a comma-separated list of flag names.
  • --remove-flags FLAG β€” remove flag(s) from read. FLAG is specified in the exact same way as with the --add-flags option, so no new rules to memorise, you're welcome πŸ’…
  • --subsample FLOAT β€” output only a proportion of the input alignments, as specified by 0.0 ≀ FLOAT ≀ 1.0, which gives the fraction of templates/pairs to be kept. And the way this works? It acts in the same way on all of the alignment records in the same template or read pair, so it never keeps a read but not its mate β€” no orphan energy here, fr fr 🫢
  • --subsample-seed INT|auto β€” the subsampling seed used to influence which subset of reads is kept. If the value is the literal string auto, the seed is derived from a hash of the input file's header text. Because each subsampling run appends an @CO header line recording the fraction and seed used (and, unless --no-PG is given, a @PG line as well), re-subsampling a file in auto mode will automatically produce a different seed at each step, ensuring the expected fraction of reads is retained. When subsampling data that has previously been subsampled using an explicit seed, be sure to use a different seed value from those used previously; otherwise more reads will be retained than expected. Default is [auto] ⭐
  • -s FLOAT β€” subsampling shorthand option, living that low-effort-high-reward life ✨ -s INT.FRAC is equivalent to --subsample-seed INT --subsample 0.FRAC. And INT may also be the literal string auto. Short and sweet.
  • -@ INT, --threads INT β€” number of BAM compression threads to use in addition to main thread [0]. Give the girl some threads and watch her go 🧡πŸ”₯
  • -P, --fetch-pairs β€” retrieve pairs even when the mate is outside of the requested region. Enabling this option also turns on the multi-region iterator (-M). A region to search must be specified, either on the command-line, or using the -L option. The input file must be an indexed regular file, no exceptions πŸ’…

So how does this overachiever work? This option first scans the requested region, using the RNEXT and PNEXT fields of the records that have the PAIRED flag set and pass other filtering options to find where paired reads are located. These locations are used to build an expanded region list, and a set of QNAMEs to allow from the new regions. It will then make a second pass, collecting all reads from the originally-specified region list together with reads from additional locations that match the allowed set of QNAMEs. Any other filtering options used will be applied to all reads found during this second pass. Two passes, one queen πŸ‘‘

As this option links reads using RNEXT and PNEXT, it is important that these fields are set accurately. Use samtools fixmate to correct them if necessary.

Not me having to say this 😭 this option does not work with the -c, --count; -U, --output-unselected; or -p, --unmap options. Just doesn't, bestie.
  • -S β€” ignored for compatibility with previous samtools versions. Previously this option was required if input was in SAM format, but now the correct format is automatically detected by examining the first few characters of input. She's retired but still on the roster 🫑
  • -X, --customized-index β€” include customized index file as a part of arguments. See the EXAMPLES section for a sample of usage πŸ‘€
  • -z FLAGs, --sanitize FLAGs β€” perform some sanity checks on the state of SAM record fields, fixing up common mistakes made by aligners. These include soft-clipping alignments when they extend beyond the end of the reference, marking records as unmapped when they have reference * or position 0, and ensuring unmapped alignments have no CIGAR or mapping quality for unmapped alignments and no MD, NM, CG or SM tags. Basically a glow-up pass for messy data πŸ§–β€β™€οΈβœ¨

FLAGs is a comma-separated list of keywords chosen from the following list:

  • unmap β€” the UNMAPPED BAM flag. This is set for reads with position <= 0, reference name "*" or reads starting beyond the end of the reference. Note CIGAR "*" is permitted for mapped data so does not trigger this.
  • pos β€” position and reference name fields. These may be cleared when a sequence is unmapped due to the coordinates being beyond the end of the reference. Selecting this may change the sort order of the file, so it is not a part of the on compound argument πŸ‘€
  • mqual β€” mapping quality. This is set to zero for unmapped reads.
  • cigar β€” modifies CIGAR fields, either by adding soft-clips for reads that overlap the end of the reference or by clearing it for unmapped reads.
  • cigdup β€” canonicalises CIGAR by collapsing neighbouring elements with identical opcodes (provided the length field does not extend beyond 28-bits which is problematic for BAM). So for example 2M 3M becomes 5M, with spaces added for clarity only.
  • cigarx β€” replaces CIGAR "=" and "X" codes with "M". While "=" and "X" are valid codes, they are not supported by CRAM so this can aid validation and also improve support by some third party tools that do not cope with "=" and "X". Note this implicitly also enables cigdup so 10=1X9= becomes 10M1M9M which then becomes 20M. Glow-up chain reaction πŸ’«
  • aux β€” for unmapped data, some auxiliary fields are meaningless and will be removed. These include NM, MD, CG and SM.
  • off β€” perform no sanity fixing. This is the default 😴
  • on β€” sanitize data in a way that guarantees the same sort order. This is everything except for pos as it cannot be checked and cigarx as it is not erroneous data.
  • all β€” all sanitizing options except cigarx, including pos. Combine with all,cigarx to perform the "=" and "X" replacement too.
  • --no-PG β€” do not add a @PG line to the header of the output file. Keep your header clean, bestie πŸŽ€

✨ EXAMPLES ✨

okay bestie, this is the part where it all clicks πŸ’… real scenarios, real commands, copy-paste certified.


πŸŽ€ Getting your SAM into BAM

If your header already has @SQ lines (the little map of your reference), you're literally one step away:

samtools view -bo aln.bam aln.sam

If the @SQ lines are NOT there β€” no worries, we build them ourselves. First index the reference:

samtools faidx ref.fa
samtools view -bt ref.fa.fai -o aln.bam aln.sam

and yes, ref.fa.fai gets generated automatically by the faidx command, so you don't have to do anything extra. she's self-sufficient πŸ’–


πŸ¦‹ BAM ➑️ CRAM (the glow-up)

Convert a BAM file to a CRAM file using a local reference sequence:

samtools view -C -T ref.fa -o aln.cram aln.bam

🌸 Keeping NM and MD tags verbatim (iykyk)

Convert a BAM file to a CRAM with NM and MD tags stored verbatim rather than calculating on the fly during CRAM decode, so that mixed data sets with MD/NM only on some records, or NM calculated using different definitions of mismatch, can be decoded without change. The second command demonstrates how to decode such a file. The request to not decode MD here is turning off auto-generation of both MD and NM; it will still emit the MD/NM tags on records that had these stored verbatim.

samtools view -C --output-fmt-option store_md=1 --output-fmt-option store_nm=1 -o aln.cram aln.bam
samtools view --input-fmt-option decode_md=0 -o aln.new.bam aln.cram
ngl, that pair of long flags is giving "I have a lot to say" but she's valid β€” it's the exact same energy, just spelled out πŸ’€

πŸ’œ Same thing, but make it compact

An alternative way of achieving the above is listing multiple options after the --output-fmt or -O option. The commands below are equivalent to the two above:

samtools view -O cram,store_md=1,store_nm=1 -o aln.cram aln.bam
samtools view --input-fmt cram,decode_md=0 -o aln.new.bam aln.cram

see? iconic comma-separated behavior. same result, fewer pixels 🫢


⭐ Custom index? bring your own

Include customized index file as a part of arguments:

samtools view [options] -X /data_folder/data.bam /index_folder/data.bai chrM:1-10

your BAM lives in one folder, your .bai lives in another, and honestly? they don't have to live together. main character energy for your index πŸ”₯


🌈 Filtering by read group

Output alignments in read group grp2 (records with no RG tag will also be in the output):

samtools view -r grp2 -o /data_folder/data.rg2.bam /data_folder/data.bam

heads up bestie: the no-RG-tag records sneak in too with this one. they're just vibing along πŸ™ˆ


πŸ“ Filtering by tag value β€” the barcode edition

Only keep reads with tag BC and were the barcode matches the barcodes listed in the barcode file:

samtools view -D BC:barcodes.txt -o /data_folder/data.barcodes.bam /data_folder/data.bam

one text file, one tag name, zero drama ✨


🧚 -r vs -d: the subtle difference

Only keep reads with tag RG and read group grp2. This does almost the same than -r grp2 but will not keep records without the RG tag:

samtools view -d RG:grp2 -o /data_folder/data.rg2_only.bam /data_folder/data.bam

so like… -d is the strict one. strict queen behavior, she doesn't let the tagless ones in πŸ‘‘


πŸ’€ Undoing samtools markdup

Remove the actions of samtools markdup. Clear the duplicate flag and remove the dt tag, keep the header:

samtools view -h --remove-flags DUP -x dt -o /data_folder/dat.no_dup_markings.bam /data_folder/data.bam

the -h keeps the header alive (don't forget it!! 😭), --remove-flags DUP clears the duplicate flag, and -x dt yeets the dt tag. de-dup marking, reversed. no cap πŸ’…


πŸ‘‘ AUTHOR

Written by Heng Li from the Sanger Institute.

(we stan. legendary. that's the origin story fr fr 🫢)


🌟 SEE ALSO

Samtools website: <http://www.htslib.org/>


and that's a wrap, bestie πŸŽ€ this page is from samtools-1.24, dated 9 July 2026, and you were reading samtools-view(1). go forth and samtools view responsibly βœ¨πŸ’–

πŸ“¦ where this page comes from