2

I have an array that contains a list of filenames (without extension) ex:

filearray=("fileA" "fileB" "fileC")

These files are split amongst multiple directories. As I loop through the directories, I would like to perform an operation on the files from the array that are present in each directory. How can I use find or grep with an array?

Can I do something like this?:

Dirarray= ("dirA" "dirB")
for Dir in "${Dirarray[@]}"; do
    cd "$Dir";
    for file in "${filearray[@]}"; do
        if find . -regextype posix-extended -regex "$file"; then;
            do X;
        fi;
     done
done

Thanks!

  • 1
    You just answered your won question in the question? Or are you having some trouble with your script? (PS: you probably need to cd back after cd "$Dir" or use subshell) – grochmal Oct 6 '16 at 22:00
  • @grochmal It looks fine to me without another cd. I corrected readability. One done was missing. – Tomasz Oct 6 '16 at 22:08
  • Sorry, I didn't say: the find statement doesn't work with the array element – Alex Oct 7 '16 at 19:02
2

I would do it in a different way.

Dirarray= ("dirA" "dirB")
for Dir in "${Dirarray[@]}"; do
    cd "$Dir"
    for file in "${filearray[@]}"; do
# Here a change. If "$file" exists...
        if [[ -e "$file"]]; then
            : # do something
        fi
     done
done

See man test for more file test options.

The reason is this way is much more simple. Well, as long as the array doesn't contain regexes.

  • Also, ${filearray[@]/#/$Dir/} instead of the cd. – Kusalananda Dec 19 '18 at 20:55

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.