Add file by (*) star character to variable in for loop

Viewed 155

I have a folder structure where two files are in a folder. The files have long names, yet are distinguished by R1 and R2. Note I am running this over many folders using the for loop but keeping it simple for this example. I am running a loop and am wonder how to correctly call the files with a (*) star character to autocomplete without having to type in all file name. My attempt is below:

#!/bin/bash

for item in Folder_Directory:
do
forward=$item/*R1*
reverse=$item/*R2*
bbmap.sh ref=reference.fna in1=$forward in2=$reverse outu=Unmapped.fasta
done

The output I am getting is an error because the variable is not identifying the desired file:

Error:

align2.BBMap build=1 overwrite=true fastareadlen=500 ref=reference.fna 
in1=Folder_Dictory/*R1* in2=Folder_Dictory/*R2* outu=Folder_Dictory/Unmapped.fastq

In this example I could autocomplete the files, however, when I expand this loop to include multiple folders that is no longer ideal. Autocompleting using (*) characters was my first approach, any other suggestions or fixes to my issue are greatly appreciated.

3 Answers

If you want only two files from your folder_structure, then i believe it would be good to use find to search for the files and assign then into separate variables as per your requirement...don't see use of for loop here.

forward=$(find Folder_Directory -type f -name "*R1*")
reverse=$(find Folder_Directory -type f -name "*R2*")
bbmap.sh ref=reference.fna in1="$forward" in2="$reverse" outu=Unmapped.fasta

The problem is that the shell sees in1=Folder_Dictory/*R1* and notices that there are no files which match the glob with the literal in1= prefix, and so the wildcard does not get expanded at all.

You probably want to evaluate the wildcard before passing it to the command, like for instance

for item in Folder_Directory:
do
  forward=$item/*R1*
  reverse=$item/*R2*
  bbmap.sh ref=reference.fna in1="$(echo $forward)" in2="$(echo $reverse)" outu=Unmapped.fasta
done

This will of course still be erratic if the wildcard expands to more than one file.

It works like this:

test=f*
$ echo $test 
file

But

$ echo "$test"
f*

And

test2=$test
$ echo "$test" $test2
f* file

$ echo "$test" "$test2"
f* f*

To make it work, you have to do something like this:

test3="$(echo $test)"
$ echo "$test" "$test2" "$test3"
f* f* file
Related