This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Using seq command in terminal with Samtools view

I am trying to create three separate bam files using Samtools View for three different regions of interest. I am using the following, but I don't get any output. Could somebody point out what is wrong? Regions_1 to 3 were used to generate bowtie indexes and the bam files.

$ for number in 'seq 1 3' ; do samtools view -bh ./Sample1_bowtie2.bam Region_${number} > ./Sample1_Amplicon${number}.bam

Any alternate suggestions?

Thank you all!

samtools shell

1 answer

for R in "chr1:10-20" "chr10:12-13" "chr20:14-15" 
do
   samtools view -b -o "${R//[\:\-]/_}.bam" input.bam "${R}" 
done

Variation: If you have a lot of regions which you have in a file listed line by line e.g.: myregions.txt

chr1:10-20
chr10:12-13
chr20:14-15

you could use the following:

for R in `cat myregions.txt`
do
   samtools view -b -o "${R//[\:\-]/_}.bam" input.bam "${R}" 
done

Thanks so much guys!

I suppose I still am a novice in this...

I tried both -

for R in "Region_1" "Region_2" "Region_3" ; do samtools view -b -o "${R//[\:\-]/_}.bam Sample1_bowtie2.bam "${R}" ; done

for R in 'cat regions.txt' ; do samtools view -b -o "${R//[\:\-]/_}.bam Sample1_bowtie2.bam "${R}" ; done

However, both seems to not work. I am guessing I'm doing something wrong here - "${R//[\:-]/_}.bam ?

Your suggestions are greatly appreciated.

both seems to not work.

Try to be more specific when reporting something isn't working, that might help us to spot the issue.

At least one error is that you used incorrect quotes in my command, around cat myregions.txt there are backtick quotes " ` ".

You can check how your command would look like using a simple echo statement, e.g. for Pierre's command:

for R in "chr1:10-20" "chr10:12-13" "chr20:14-15" 
do
   echo samtools view -b -o "${R//[\:\-]/_}.bam" input.bam "${R}" 
done

And then check if the outputted command is as you would expect it. Easier for troubleshooting.

Thanks, WouterDeCoster!

For echo I get - -bash: syntax error near unexpected token `echo'

Also, with the commands Pierre and Wouter suggested, I see > with a blinking cursor next to it.

Are you properly adding newlines as in our code examples? They play a role here.
Alternatively, try the following:

for R in "chr1:10-20" "chr10:12-13" "chr20:14-15" ;
do
   echo samtools view -b -o "${R//[\:\-]/_}.bam" input.bam "${R}" ;
done

(Added semicolons)

Thank you, WouterDeCoster! I think it's a silly question. But, do I run these commands directly in terminal or I have to make a script? If it is a script, how do I invoke it in terminal?

You could do both, but there is no need to make a script. You can just run these commands in the terminal.

Log in to answer this question.