I have a parent directory with multiples subdirectories like this


And I would like to run the perl scipt in each subdirectory. I'm trying with the next command

find . -type d | while read d; do perl hoz-3-v1c.pl $d/* ; done

but the output is directed to the parent directory and I want the output in each subdirectory


It looks like you don't have to bother with find at all in this instance.

for dirpath in Parent_directory/*/; do
    ( cd "$dirpath" && perl perlscript.pl *.fasta )

This assumes that the Perl script is always called perlscript.pl (as in your example directory layout) and that correct way to run your Perl script inside each directory is

perl perlscript.pl *.fasta

In the loop above, the parentheses creates a subshell. This prevents the cd from affecting the rest of the script and we don't have to cd back out of the directory after running the Perl script.

The loop will iterate over all subdirectories of Parent_directory and execute the given commands in each.

|improve this answer|||||

If your find supports the -execdir predicate (GNU, BSDs at least):

find . -name perlscript.pl -execdir sh -c 'exec perl ./perlscript.pl *.fasta' \;

searches for the perlscript.pl files and runs perl on it with the current directory set to the directory where it's found.

We need a shell to expand the *.fasta glob.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.