Question: Writing a bash loop to convert sams to bams
0
gravatar for raf.marcondes
13 months ago by
raf.marcondes30 wrote:

Hey all, I'm trying to write a small bash loop to iterate over all sam files in a directory converting them to bam. What I have so far is:

files=$(ls)
for f in "$files"
    do samtools view -S -b $f>"$f".bam
    done

But what I get when I run that is:

convert_sam_to_bam.sh: line 9: ACGGTC.1.sam
AGACCA.1.sam
AGCTTT.1.sam
AGGAAT.1.sam
[list of all sams in the directory]
TGACAT.1.sam
TTAGGC.1.sam
TTGACT.1.sam
TTGTCA.1.sam.bam: File name too long

I'm sure the problem is that I'm messing up with the quotations somewhere, but I can't for the life of me figure out where. Any thoughts? Thanks a lot in advanc!

alignment • 360 views
ADD COMMENTlink modified 13 months ago by st.ph.n2.5k • written 13 months ago by raf.marcondes30
1

This is a pure shell question. For starters, you don't need files=$(ls); for f in $files, you can simply do for f in * (or better, for f in *.sam). In fact, I think doing that will solve your problem as your current approach treats a set of filenames as a string instead of treating it as an array.

ADD REPLYlink modified 13 months ago • written 13 months ago by RamRS27k
1
gravatar for st.ph.n
13 months ago by
st.ph.n2.5k
Philadelphia, PA
st.ph.n2.5k wrote:
for file in *.sam; do
    samtools view -S -b $file > "`basename $file .sam`.bam"
done
ADD COMMENTlink written 13 months ago by st.ph.n2.5k
1

You don't need the basename sub-shell call, you can simply use ${file/%sam/bam}. Bash has powerful parameter expansion.

ADD REPLYlink written 13 months ago by RamRS27k
Please log in to add an answer.

Help
Access

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.
Powered by Biostar version 2.3.0
Traffic: 1436 users visited in the last hour