Files
q-tools/folderSplitter
2015-04-23 09:55:21 +03:00

69 lines
1.3 KiB
Bash
Executable File

#!/bin/bash
function helpexit() {
echo "FolderSplitter: copy files in this folder to subfolders in equal distribution"
echo "usage: FolderSplitter [numberOfFolders] [rootFolder]"
echo " If rootFolder omitted, current working directory used "
exit
}
[[ -z "$1" ]] && helpexit
[[ "$1" = "-h" ]] && helpexit
if [ -z "$2" ]
then indir=$( pwd )
else
if [ -d "$2" ]
then indir="$2"
else
echo $2 does not exist.
exit 1
fi
fi
if [ -z "$1" ]
then echo need a number to how many folders to split.
exit 1
fi
if [[ $1 == +([0-9]) ]]
then n=$1
else
echo $1 is not integer
exit
fi
# make the list separator a rowchange
IFS=$'\n'
# list files
pushd "$indir"
infiles=( $( ls ) )
fip=0
# create directories
for (( d=1; d<=$n; d++ ))
do str="dir"$d
mkdir "${str}" || echo error creating directory ${str}
done
perdir=$(( ${#infiles[@]} / $n ))
dip=1
fip=1
for (( f=0; f<${#infiles[@]}; f++ ))
do cp -lav "${infiles[$f]}" dir"$dip"/ || echo error copying file ${infiles[$f]}
if (( $fip > $perdir ))
then dip=$(($dip+1))
fip=1
else
fip=$(($fip+1))
fi
if (( $dip > $n ))
then dip=$n
fi
done
for (( d=1; d<=$n; d++ ))
do echo "dir"$d with $( ls dir"$d" | wc --lines ) files
done