Parallel xargs by Chr
This applet slices a BAM file by canonical chromosome then performs a parallelized samtools view -c using xargs. Type man xargs for general usage information.
Last updated
Was this helpful?
Was this helpful?
# Download BAM from DNAnexus
dx download "${mappings_bam}"
# Attempt to index the BAM file
indexsuccess=true
bam_filename="${mappings_bam_name}"
samtools index "${mappings_bam_name}" || indexsuccess=false
# If indexing fails, sort then index
if [[ $indexsuccess == false ]]; then
samtools sort -o "${mappings_bam_name}" "${mappings_bam_name}"
samtools index "${mappings_bam_name}"
bam_filename="${mappings_bam_name}"
fi
# Extract chromosome names from header
chromosomes=$(
samtools view -H "${bam_filename}" | \
grep "@SQ" | \
awk -F '\t' '{print $2}' | \
awk -F ':' '{
if ($2 ~ /^chr[0-9XYM]+$|^[0-9XYM]/) {
print $2
}
}'
)
# Split BAM by chromosome and record filenames
for chr in $chromosomes; do
samtools view -b "${bam_filename}" "${chr}" -o "bam_${chr}.bam"
echo "bam_${chr}.bam"
done > bamfiles.txtcounts_txt_name="${mappings_bam_prefix}_count.txt"
# Sum all read counts across split BAM files
sum_reads=$(
< bamfiles.txt xargs -I {} \
samtools view -c $view_options '{}' | \
awk '{s += $1} END {print s}'
)
# Write the total read count to a file
echo "Total Count: ${sum_reads}" > "${counts_txt_name}"counts_txt_id=$(dx upload "${counts_txt_name}" --brief)
dx-jobutil-add-output counts_txt "${counts_txt_id}" --class=file