0

The problem:

Hi, I'm trying to loop over each *.faa file in multiple directories (e.g. /path/to/*.faa)

And then, using a script (./script.py) as if the script was in the same directory as the *.faa file, is this possible with shellscript?

What I've tried:

for FAA in $(find . -name "*.faa")
do
    cd ../$FAA
    python3 ../script.py
done

I've tried variations on this, but changing to the directory to a file doesn't work, but I don't know a way of getting to that directory.

Desired output:

For each .faa file, in multiple directories e.g /path/to/1.faa, path/2/2.faa, run the script in the directory two levels above. As if it were in the same directory as each of the *.faa files, or if that's not possible, what is the best solution to achieving something similar?

Biomage
  • 145
  • 1
    You say "two levels above", but also "as in the same directory"? I'm not exactly sure what you mean, can you [edit] to add some sort of an example. E.g. if you /some/path/to/foo.faa, what directory do you want to go to run the script? – ilkkachu Jul 06 '18 at 10:07
  • Do you mean you have /some/path/script.py that should be the one that runs for /some/path/to/foo.faa? – ilkkachu Jul 06 '18 at 10:09
  • As you move around different directory depths, your relative path to script.py will need to change (./ or ../ or ../../, etc.). Can you provide an absolute path to the script please. (At least, an example one.) – Chris Davies Jul 06 '18 at 10:09

1 Answers1

0
find . -type f -name '*.faa' -execdir python3 ../script.py ';'

This would execute python3 ../script.py with the directory of each found file as working directory.

Since your words and your code is somewhat conflicting, I'm not sure whether it should be ../script.py or ../../script.py.

Note too that this would only work if the script.py file is actually available in the indicated directory. It may be safer to provide an absolute path to the script file:

find . -type f -name '*.faa' -execdir python3 /path/to/script.py ';'

The above would execute the script for each found file, even if there are multiple .faa files in a directory. To execute the script only once for each directory that has at least one .faa file in it:

find . -type d -exec sh -c '
    for dir do
        set -- "$dir"/*.faa
        if [ "$#" -gt 0 ]; then
            ( cd "$dir" && python3 /path/to/script.py )
        fi
    done' sh {} +

This would execute a short shell script for each found directory. The script peeks into the directory to see if there are any .faa files in there. If there is, the Python script is executed with that directory as working directory.

Related:

Kusalananda
  • 333,661