1

I have two arrays which has file numbers and I need to read those two arrays and delete those files. I need to read pri array and delete files inside /primary directory. Similarly I need to read snd array and delete files inside /secondary directory. These two directories have lot of other files and other subdirectories as well so I need to be very careful. I just need to delete files which are mentioned in those two arrays only.

All file names are like this:

abc_monthly_5_log.data
abc_monthly_25_log.data
abc_monthly_78_log.data

Below is my script and I can iterate them and delete those files one by one. Is there any other better way by which I can do that?

# it will lot of file numbers not just four or five files
pri=(0 5 7 100)
snd=(9 8 187 90 156)

# iterate pri array and delete files inside
for pm in "${pri[@]}"; do
    rm /primary/abc_monthly_"$pm"_log.data
done

# iterate snd array and delete files inside
for sm in "${snd[@]}"; do
    rm /secondary/abc_monthly_"$sm"_log.data
done
1
  • 2
    Looks like a reasonable solution. Your code is clean and immediately understandable. Unless you have serious performance problems I don't see why you would want to change it. May 2, 2018 at 5:21

1 Answer 1

2

A "better" way, which is "better" in that it executes rm less often, would be to use xargs:

{
    for pm in "${pri[@]}"; do
        printf '/primary/abc_monthly_%s_log.data\n' "$pm"
    done

    for sm in "${snd[@]}"; do
        printf '/secondary/abc_monthly_%s_log.data\n' "$sm"
    done
} | xargs rm

This would use the loops just as a mean for generating pathnames. These pathnames are then passed to xargs rm which would execute rm on as many of them as possible at once. With the example arrays that you have provided, it would probably just run rm once.

The way I have written it above assumes that none of the path components contain literal newlines or whitespace (which they don't do in this example).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .