3

I wanted to extract specific lines from multiple bam (a binary file format) files. I can select the lines from a single bam file using this command:

samtools view -c TCGA-BH-A0BW-11A.sorted.bam "5:13744354-13744380"
550

I have a directory with 100 bam files like below:

TCGA-AC-A2FB-11A.sorted.bam
TCGA-AC-A2FF-11A.sorted.bam
TCGA-AC-A2FM-11B.sorted.bam
TCGA-AC-A2QH-01A.sorted.bam
TCGA-AC-A2QJ-01A.sorted.bam
TCGA-BH-A0BW-11A.sorted.bam
TCGA-BH-A0BW-01A.sorted.bam
TCGA-CH-A0BW-11A.sorted.bam

How do I apply the command to multiple bam files and save the output in a single file with the first column as the file name without the extension and the second column being the result of the samtools command on this file?

For example: It should somehow look like this

TCGA-BH-A0BW-11A     550
TCGA-BH-A0BW-01A     220
TCGA-CH-A0BW-11A     100

I am working on a Linux system.

1
  • Remember that people here are not bioinformaticians, so don't expect them to know what reads are or what bam files are. When asking here, make sure that someone with no knowledge of bioinformatics has enough information to answer the question (as I did with my edit). By the way, you might be interested in our sister site: Bioinformatics. – terdon Aug 3 '20 at 15:19
4

If you are using bash, you can iterate over all files with the appropriate extension, and process them as follows:

for file in *.sorted.bam
do
    key="${file%.sorted.bam}"
    value="$(samtools view -c "$file" "5:13744354-13744380")"
    echo "$key $value"
done > output.txt

In the loop, we

  • generate the file key by removing .sorted.bam from the end of the filename (and store it in a shell variable key)
  • perform the processing as shown in your single-file example and store the output in a shell variable value
  • print both key and value

and redirect the overall output of the loop to a file output.txt.

1
  • Thanks a lot for the quick and well informative reply. – beginner Aug 3 '20 at 15:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.