Copy files to subfolders based on first 3 characters of filename

I’m seeking a way to copy files from a folder to subfolders based on the first 3 characters of the filename.

For example, my root folder “images” contains diverse filenames like so:

1234567.jpg
abcdefg.jpg
ertfge34-893.jpg
etc.

The script will create multiple levels of subfolders in a new folder (imagesnew) if they don’t already exist and move the files to the created folders like so:

1234567.jpg → imagesnew/1/2/3/1234567.jpg
abcdefg.jpg → imagesnew/a/b/c/abcdefg.jpg
ertfge34-893.jpg → imagesnew/e/r/t/ertfge34-893.jpg

Any help with this would be hugely appreciated!

THANKS

Hi,

try this


property baseFolder : "Mac HD:path:to:folder:" -- the colon at the end is crucial
property deleteOriginals : true -- set to false to keep the original files

set theItems to list folder baseFolder without invisibles

repeat with oneItem in theItems
	set {name:Nm, folder:Fo, package folder:Pa} to (info for file ((baseFolder as text) & oneItem))
	if not Fo or Pa then
		set {TID, text item delimiters} to {text item delimiters, "/"}
		set destFolder to (characters 1 thru 3 of Nm & Nm) as text
		set destination to quoted form of (POSIX path of baseFolder & destFolder)
		set text item delimiters to TID
		do shell script "ditto " & quoted form of ((POSIX path of baseFolder) & oneItem) & " " & destination
		if deleteOriginals then do shell script "rm -r " & quoted form of ((POSIX path of baseFolder) & oneItem)
	end if
end repeat

Stefan,

It worked perfectly!

I want to thank you so much. I’m awed by your skill and generosity. Please let me know if I can offer you anything in return.

Best,
Jason

You’re welcome.

I wrote a similar script some months ago, which I had just to modify a bit.
There is a big advantage using ditto, which creates the intermediate directories silently

Nice work Stefan, I had something similar worked out and then spiraled down the path of keeping it all in the shell LOL

I can immagine that a pure shell version is the best solution but unlike AppleScript my UNIX knowledge is much more limited

My only problem with the script thus far is that Mac assumes upper and lower-case chars to be the same. Since, I will need these files served on the Internet, character-case will be necessary.

For example:
abc123.jpg served from /A/b/c/abc123.jpg will be a broken URL.

The script is placing both abc123.jpg and Abcdef.jpg in: /A/b/c/

Stefan, here’s a purely shell version

set baseFolder to POSIX path of (choose folder with prompt "Select your source folder please")
set destFolder to POSIX path of (choose folder with prompt "Where should I make \"imagesnew\" ?")

do shell script "cd " & quoted form of baseFolder & "; find . -type f -name '*.jpg' | sed -e 's%\\(.//*\\)\\(.\\)\\(.\\)\\(.\\)\\(.*\\)%ditto \\1\\2\\3\\4\\5 " & quoted form of (destFolder & "imagesnew") & "/\\2/\\3/\\4/%' | sh"