Shreyas S C
Shreyas S C

Reputation: 11

How do I move a large number of zip files in a directory to a specified number of multiple subdirectories in bash?

In the current directory there are many hundreds of .zip files. Also in this directory are six subdirectories named 0 through 5. The .zip files need to be evenly distributed (or as near as possible) and moved into these subdirectories. I don't care which files end up in which subdirectories as long as they're evenly distributed.

How do I try to achieve this. Should i make use of maxdepth and try to find the count of the subdirectories and then place the files recursively or how do I go about?

Upvotes: 0

Views: 182

Answers (1)

chw21
chw21

Reputation: 8140

Here's a quick and dirty solution: For every zip file, increment the target directory number by one, then move it there.

If the target directory number isn't available any more, reset the target directory number.

#!/usr/bin/env bash

declare -i i=0
for f in *.zip; do
    mv ${f} ${i}/
    i=$i+1
    if [[ ! -d $i ]]; then
        i=0 
    fi
done

Now note that this is not at all foolproof, and it spawns a separate move process for every file. If you need to do this only once, I think it's not worth spending any more brain cells on than this. However, if that's something you want to do on a regular basis, you should think about what kind of errors could happen, and how to catch them, and maybe even look at more effective movement.

Upvotes: 1

Related Questions