cesmarch cesmarch - 7 months ago 7
Bash Question

How to move all the files of a directory into multiple directories with a given number of files?

I have a directory containing more than 27000 images.

I want to split these files into folders each containing around 500 images.

It doesn't matter how they are sorted, I just want to separate them.

Answer

The following should work:

dest_base="destination"
src_dir="src/"

atfile=0
atdir=0
for file in $src_dir/*; do
    if ((atfile == 0)); then
        dest_dir=$(printf "$dest_base/%0.5d" $atdir)
        [[ -d $dest_dir ]] || mkdir -p $dest_dir
    fi
    mv $file $dest_dir
    ((atfile++))
    if ((atfile > 500)); then
        atfile=0
        ((atdir++))
    fi
done