56438d61fd1c1b7d352a12c9b402f4a9

Hi Guys,

The Website I'm working for has 400 photos to publish. For each of the 400 photographs, there are 4 images named like so: website-hi_res-1.jpg, website-lo_res-1.jpg, website-preview-1.jpg, website-thumbnail-1.jpg (The number in the filename increments for each photograph). The four images for each photograph then need to be sorted into their own folder, for example images - website-hi_res-1.jpg, website-lo_res-1.jpg, website-preview-1.jpg, website-thumbnail-1.jpg - get sorted into folder "1". The folders are then compressed into zip archives, 10 folders at a time.

I wrote the following script (with some help from the http://www.newcastlelug.org/ guys) for my Mac at work to speed up the process, but I think it could be a little better.

The script actually gets called from a simple AppleScript script that has been saved as an App.

#!/bin/bash

# Get into the right folder
cd ~/Website\ Photographs/

# Create input folder
if [[ ! -d "input" ]]; then
	mkdir -p input
fi

# Create sorted images folder
if [[ ! -d "sorted" ]]; then
	mkdir -p sorted
fi

# Create archives folder
if [[ ! -d "archives" ]]; then
	mkdir -p archives
fi

# Create fake image files to process for testing purposes
for i in `seq 1 20`; do
	touch input/ironbark-hi_res-${i}.jpg;
	touch input/ironbark-lo_res-${i}.jpg;
	touch input/ironbark-preview-${i}.jpg;
	touch input/ironbark-thumbnail-${i}.jpg;
done

# Count fake image files
CI=`ls input/ | wc -w`;
echo "Created ${CI} fake image files..."

# Sort the files automatically into folders
for f in input/*.jpg; do
	DIR=`echo ${f} | cut -d '-' -f 3`;
	DIR=`echo ${DIR} | cut -d '.' -f 1`;
	if [[ ! -d "sorted/${DIR}" ]]; then
		mkdir -p sorted/${DIR};
	fi
	mv ${f} sorted/${DIR};
done

# Count sorted sub folders
CS=`ls sorted/ | wc -w`;
echo "Sorted ${CI} fake image files into ${CS} sub folders...";

# Jump into the sorted folder and archive stuff
cd sorted/

# Proceed to archive the contents of sorted 10 folders at a time
ls -1 | sort -g | xargs -L10 | while read first rest
do
	zip -9r ../archives/archive_${first}.zip ${first} ${rest}
        rm -rf ${first} ${rest}
done

# Get out of sorted
cd ..
on run
    tell app "Terminal"
        activate
        display dialog "This will sort and archive all the images in folder: ~/Website Photographs.\nAre you sure you want to continue?"
        do script "bash ~/sort_pics.sh"
    end tell
end run

Refactorings

No refactoring yet !

Ee0505bbd355292778077fb662c88f13

Fu86

June 21, 2010, June 21, 2010 10:36, permalink

No rating. Login to rate!

You dont need the if tests for the folder creation. The manpage for mkdir says:

-p, --parents
no error if existing, make parent directories as needed

So, if the folder allready exists, mkdir does nothing.

mkdir -p {input,sorted,archives}

Your refactoring





Format Copy from initial code

or Cancel