Bash script for creating a folder structure – for fun and … science!

24 Aug

I’ve been sorting/renaming a lot of images of Quinoa lately for plant phenotyping. To help with this, here is a small script. The idea is to create a folder structure into which photos can be dragged and dropped. The images can then be renamed/processed based on the folder structure (or accessed as they are), rather than sorting and renaming all the images manually. With 1000s of images per experiment, it’s the quickest and less error prone method I could find.

For example:
You have an unknown number of images from each of 1600+ field plots. Thankfully the images are in order based on the file name. Simply drag and drop the groups of images from each plot into the appropriate folder. This is still a manual option, but it is much quicker than renaming and/or creating folders as you go.

Here’s the script (.zip): create_folders.zip

To run:

#to create folders from plot_1 to plot_1600, with sub-folders "keep" and "discard"
./createfolders.sh plot 1600 keep discard 

Here’s the code:


#!/bin/bash
# Script for creating folder structure (for image sorting)

display_usage() { 
	echo
	echo "Usage: create_folders.sh [folderPrefix totalNumberofFolders subfolder_1 subfolder_2 .. subfolder_n]"
	echo "will produce folder structure in folder OUTPUT:"
	echo "Create folders named folderPrefix_1 to folderPrefix_TotalNumberOfFolders"
	echo "each containing sub-folders: subfolder_1 subfolder_2 .. subfolder_n"
} 
	
# if less than two arguments supplied, display usage 
if [  $# -le 1 ] 
then 
	display_usage
	exit 1
fi 
 
folderPrefix=$1;
TotalNumberOfFolders=$2;

echo "will produce folder structure in folder OUTPUT:"
folderOne=$folderPrefix"_1"
folderTwo=$folderPrefix"_"$TotalNumberOfFolders
echo "Create folders named $folderOne to $folderTwo ($TotalNumberOfFolders folders in total)"
echo "each containing sub-folders:"
for var in ${@:3}
do
    echo "$var"
done
echo
read -rsp $'Press any key to continue...\n' -n 1 key
# echo $key
rm OUTPUT -rf #removes previous folder structure
mkdir OUTPUT;
cd ./OUTPUT;
for ((idx = 1; idx <= $TotalNumberOfFolders; idx++)); do 
	folderName=$folderPrefix"_"$idx
	echo "mkdir $folderName";	
	mkdir $folderName
	for var in ${@:3}
	do
		echo "mkdir $folderName/$var"
		cd $folderName
		mkdir "$var"
		cd ..
	done
done

Print Friendly, PDF & Email

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.