Divide files into folders and zip them

I have a set of files that I usually have to divide into multiple folders and zip them together so I can upload on the cloud. It’s been a long time I’ve been manually doing this but then I thought I’d rather automate this altogether. So now all I have to do is calculate how many folders I need and a prefix for the folder, e.g. Color or BW and the program does the rest for me. It creates the folders, equally divides the files into those folders and zip them. Once the program finishes execution, I’m ready to upload them.

#/usr/bin/bash

# Enter number of folders to be created
# The program will create those folders and divide and move the files equally within those folders

# Exit if number of folders not provided
if [[ $1 -eq 0 ]]; then
	echo 'Enter number of folders to be created'
	exit 0
fi

# Exit if folder_previx is not provided
if [[ $2 = '' ]]; then
	echo 'Enter the prefix for the folder, e.g. Color or BW'
	exit 0
fi

# Get total number of files in directory
file_count=`ls -lrt *.jpg | wc -l`
echo Total files: $file_count

num_folders=$1
files_per_folder=$((file_count / num_folders))
files_per_folder=$((files_per_folder+1))
echo Files per folder: $files_per_folder

# Create folders; Divide and move images to folders and zip them so they are ready to upload
for ((i=1; i<=$num_folders; i++)); do
	if [[ $i -lt 10 ]]; then
		mkdir $2-Part0$i
		find . -name "*.jpg" -maxdepth 1 -type f | head -$files_per_folder | xargs -I{} mv {} $2-Part0$i
		zip -r $2-Part0$i.zip $2-Part0$i
	else
		mkdir $2-Part$i
		find . -name "*.jpg" -maxdepth 1 -type f | head -$files_per_folder | xargs -I{} mv {} $2-Part$i
		zip -r $2-Part$i.zip $2-Part$i
	fi
done
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s