Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

Click here to return to the 'Flatten a folder's structure via AppleScript' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Flatten a folder's structure via AppleScript
Authored by: jbc on May 30, '09 08:11:03AM

Stumbled across this thread while researching a script for reorganizing some really unwieldy folder structures and 30,000 files, Thought I'd post back with my results in case it's useful to any one. I decided on a shell script version; it ended up being much faster than the Applescript versions I tried.

My basic goal was to flatten all files to the main folders, but for the larger folders (containing up to 4000 files) I wanted to sort the files into alphabetical subfolders. I decided on running the script as a contextual menu item using OnMyCommand, so all selected folders in the Finder are passed to the script one at a time. So if you're using Applescript or Platypus to set up a droppable app or whatever you'll need to set up the folder handling.

Note that I used a Macports-installed version of GNU mv (gmv) for moving files, since the default mv on my Tiger setup doesn't support the "--backup" option. The script moves any duplicates found to a folder named "Duplicate". Also any invisible dot files (like .DS_store) in the main folder should be preserved; any in subfolders will be deleted.

cd __OBJ_PATH__
## ^^^^^^^^^^^^ change pwd to selected folder - specific to OnMyCommand usage!

## Flatten files to selected folder, tagging duplicates
find . -mindepth 2 -type f -not -name ".*" -print0 | xargs -0J % gmv --backup=numbered % .
find . -mindepth 1 -type d -print0 | xargs -0 rm -rf

## If duplicate files were tagged, store in new folder "Duplicate"
FILES=`find . -type f -regex ".*\.[\~0-9]*"`
if [[ $FILES ]]; then
	mkdir ./Duplicate
	echo "$FILES" | tr "\n" "\0" | xargs -0J % gmv % ./Duplicate

## If over 500 files, sort files into new alphabetical folders based on first character of filename
declare -i FILECOUNT=`find . -type f -not -name ".*" | wc -l`
if [[ $FILECOUNT -ge 500 ]]; then
	for CHAR in A B C D E F G H I J K L M N O P Q R S T U V W X Y Z; do
		FILES=`find . -maxdepth 1 -type f -iname $CHAR"*"`
		if [[ $FILES ]]; then
			mkdir ./$CHAR
			echo "$FILES" | tr "\n" "\0" | xargs -0J % gmv % ./$CHAR

## Sort any remaining files into new "0-9" folder
	FILES=`find . -maxdepth 1 -type f -not -name ".*"`
	if [[ $FILES ]]; then
		mkdir ./0-9
		echo "$FILES" | tr "\n" "\0" | xargs -0J % gmv % ./0-9

[ Reply to This | # ]