How could I extract reads from bam files by their read groups @RG ?, I've got one file containing all reads for 5 samples, the SM is appears NONE, So, I want to extract each sample reads by the @RG tags.
Typically I use samtools for operations like this. Specifically I use
samtools view with either
-R flag depending on the use case.
-r 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. -R FILE Output alignments in read groups listed in FILE [null]. Note that records with no RG tag will also be output when using this option. This behaviour may change in a future release.
This sounds more like a job for
samtools split if you want to split out all the read groups into separate bams in one go.
samtools split [options] merged.sam|merged.bam|merged.cram Splits a file by read group. Options: -u FILE1 Put reads with no RG tag or an unrecognised RG tag into FILE1 -u FILE1:FILE2 As above, but assigns an RG tag as given in the header of FILE2 -f STRING Output filename format string (see below) ["%*_%#.%."] -v Verbose output
Alternatively if you do want to proceed one read group at a time, in addition to
samtools view, you can also do this with GATK using the PrintReads tool with the ReadGroupReadFilter as documented here:
The command line would look like this:
gatk PrintReads \ -I input.bam \ --read-filter ReadGroupReadFilter \ --keep-read-group <RG:readgroup> \ -O output.bam
There's also a filter called ReadGroupBlackListReadFilter that allows you to exclude a list of readgroups.
The PrintReads tool doc is here: