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"

I have a directory with 100 bam files like below:


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.

  • 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
    Commented Aug 3, 2020 at 15:19

1 Answer 1


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
    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.

  • Thanks a lot for the quick and well informative reply.
    – beginner
    Commented Aug 3, 2020 at 15:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .