1

I want to make a loop to run over multiple input files and produce one output file per input file.

I can use this command to make 1 output bam files, from 1 input sam file:

samtools view -S -b -h $input_file > $output_file

where:

input_file="/scratch/RNAseq/hisat2_alignment/456.sam"
output_file="/scratch/RNAseq/BAM_files/raw_BAM/456.bam"

When making this command into a loop I am unsure of what to do with the $output_file equivalent. Because I don't know how to make the file path and file extension change required for the $many_output_file variable:

many_input_files="/scratch/RNAseq/hisat2_alignment/*.sam"

for i in $many_input_files
do 
samtools view -S -b -h $i > $many_output_file
done

Can anyone help please? I am new to Bash, I usually use R. I have tried using sed and tr but they seem to come up with errors when I try to make the file list of many_output_file from many_input_files

Alicia
  • 57
  • 1
  • 9
  • 2
    Have you tried `samtools view -S -b -h $i > ${i/hisat2_alignment/BAM_files/raw_BAM}`? It should have worked. – oguz ismail Aug 20 '20 at 16:37
  • Thank you @oguzismail ! That has successfully changed the directory path. How can I change the file extension from .sam in the input file to .bam in the output file? – Alicia Aug 20 '20 at 16:54
  • 2
    @Alicia Look at the replacement part of what oguz wrote and see if you can't figure that out. Assign a temporary variable if needed: `tmp=${i/hisat2_alignment/BAM_files/raw_BAM}` and `with_new_ext=${tmp/old/new}`. Read about [parameter expansion](https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html) for more options. – Ted Lyngmo Aug 20 '20 at 17:04

1 Answers1

1

This is how I made the loop work, thanks to the help in the comments:

for i in $input_files
do
tmp=${i/hisat2_alignment/BAM_files/raw_BAM}
samtools view -S -b -h $i > ${tmp/.sam/.bam}
done
Alicia
  • 57
  • 1
  • 9