fabioln79
fabioln79

Reputation: 395

bash: for loop, two variables linked

I've the following problem; two directories that containing:

file1.fq file2.fq file3.fq

and so on..

file1.fq.sa file2.fq.sa file3.fq.sa

what I have to do is running a command that uses file1.fq and file1.fq.sa together.

I've tried the following loop:

fq=dir1/*
sa=dir2/*

for fqfiles in $fq;

do

for sa_files in $sa;

do

mycommand ${sa_files} ${fqfiles} > ${sa_files}.cc &

done

done

The problem is that my loop execute the following:

mycommand file1.fq.sa file1.fq > file1.fq.sa.cc  #correct

but also

mycommand file1.fq.sa file2.fq > file1.fq.sa.cc  #wrong!

and so on...in a almost infinite loop!

I wish my loop could produces something like:

mycommand file1.fq.sa file1.fq > file1.fq.sa.cc
mycommand file2.fq.sa file2.fq > file2.fq.sa.cc
mycommand file3.fq.sa file3.fq > file3.fq.sa.cc

etc...

Could you please help me?

Thank you!

Fabio

Upvotes: 1

Views: 973

Answers (1)

Olaf Dietsche
Olaf Dietsche

Reputation: 74018

You can loop over dir1, use basename on the files and then prefix with dir2 and append the extension you need. You might also want to check for the files in the second directory and run your command only if both files are available

for f in dir1/*.fq; do
    b=$(basename "$f")
    f2=dir2/"$b".sa
    if test -f "$f2"; then
        mycommand "$f2" "$f" >"$b".sa.cc
    fi
done

If you don't want the directory parts, use this one instead

mycommand "$b".sa "$b" >"$b".sa.cc

Upvotes: 1

Related Questions