Shell – Batch copy to multiple directories

cpshellxargs

I have about 9000 files in a directory and I want to mv them into 90 files in 100 directories by filename order, ignoring any remainder. In Copy multiple files from filename X to filename Y?, Caleb wrote in a comment:

If the object is just to batch them, there is a MUCH easier way! ls | xargs -iX -n20 cp X target_folder/ would run cp on files in batches of 20 until they were all done.

So based off of using xargs, how could I switch the target_folder to create a new folder and loop the command 100 times?

Best Answer

In bash, try the following code :

#!/bin/bash

c=0

for f; do
    if ! ((c % 100)); then
        folder=folder_$(printf "%03d\n" $c)
        mkdir -p $folder
    fi

    [[ -d "$f" ]] || mv "$f" "$folder"
    ((c++))
done

Run the script like that :

./script.bash *
Related Question