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 namedchr1(i.e.@SQ SN:chr1).chr2:1000000β The region onchr2beginning at base position 1,000,000 and ending at the end of the chromosome.chr3:1000-2000β The 1001bp region onchr3beginning 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:-Tis 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-poption is ignored in this mode. Counting era, but please note-pgets ignored here. π--save-counts FILEβ Save data on the number of records processed, accepted and rejected by any filter options toFILE. 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-pairsoption, 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 toFILE[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 toFILE. 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-delimitedFILE. 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>.faican be used as thisFILE. Tab-delimited reference lore. π-T FILE,--reference FILEβ A FASTA format referenceFILE, optionally compressed bybgzipand ideally indexed bysamtools 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 BEDFILE[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-Loption. 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 BEDFILE. Equivalent to-M -L FILEor--use-index --target-file FILE. Same energy, shorter spelling. β¨-N FILE,--qname-file FILEβ Output only alignments with read names listed inFILE. IfFILEstarts with^then the operation is negated and only outputs alignment with read groups not listed inFILE. 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 groupSTR[null]. Note that records with noRGtag 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 inFILE[null]. IfFILEstarts with^then the operation is negated and only outputs alignment with read names not listed inFILE. It is not permissible to mix both the filter-in and filter-out style syntax in the same command. Note that records with noRGtag 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 tagSTR1and associated valueSTR2, 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 tagSTRand associated values listed inFILE[null]. Tag values from a file, cute. π-q INT,--min-MQ INTβ Skip alignments with MAPQ smaller thanINT[0]. MAPQ gatekeeping, but make it numeric. π₯-l STR,--library STRβ Only output alignments in librarySTR[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 expressionSTR. The syntax for these expressions is described in the mainsamtools(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 inFLAGpresent in theFLAGfield.FLAGcan be specified in hex by beginning with0x(i.e./^0x[0-9A-F]+/), in octal by beginning with0(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 theFLAGfield. And how do you write FLAG? So many options, pick your fave: hex by starting with0x(i.e./^0x[0-9A-F]+/), octal by starting with0(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 theFLAGfield. FLAG is written exactly the same way as above: hex starting with0x(i.e./^0x[0-9A-F]+/), octal starting with0(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 inINTare present in theFLAGfield. It's literally the opposite of-f, so-f12 -G12is the same as no filtering at all β they cancel each other out, iconic. FLAG can be hex starting with0x(i.e./^0x[0-9A-F]+/), octal starting with0(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-tagand--remove-tagare specified then--keep-taghas 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 with0x(i.e./^0x[0-9A-F]+/), octal by beginning with0(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-flagsoption, so no new rules to memorise, you're welcome π--subsample FLOATβ output only a proportion of the input alignments, as specified by0.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 stringauto, the seed is derived from a hash of the input file's header text. Because each subsampling run appends an@COheader line recording the fraction and seed used (and, unless--no-PGis given, a@PGline as well), re-subsampling a file inautomode 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.FRACis equivalent to--subsample-seed INT --subsample 0.FRAC. AndINTmay also be the literal stringauto. 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-Loption. 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, --unmapoptions. 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 noMD,NM,CGorSMtags. Basically a glow-up pass for messy data π§ββοΈβ¨
FLAGs is a comma-separated list of keywords chosen from the following list:
unmapβ theUNMAPPEDBAM flag. This is set for reads with position <= 0, reference name"*"or reads starting beyond the end of the reference. NoteCIGAR"*"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 theoncompound 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 example2M 3Mbecomes5M, 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 enablescigdupso10=1X9=becomes10M1M9Mwhich then becomes20M. Glow-up chain reaction π«auxβ for unmapped data, some auxiliary fields are meaningless and will be removed. These includeNM,MD,CGandSM.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 forposas it cannot be checked andcigarxas it is not erroneous data.allβ all sanitizing options exceptcigarx, includingpos. Combine withall,cigarxto perform the"="and"X"replacement too.
--no-PGβ do not add a@PGline 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
- epel 10: samtools 1.24-2.el10_3 Β· MIT
- nixpkgs unstable: samtools 1.24
- Copyright (C) 2008-2011, 2013-2022, 2024, 2026-25 Genome Research Ltd
- copyright (C) 2010, 2011 Broad Institute
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms