Applescript: Move files to folder with the same first 5 characters

Suppose I have the following files in folder “A”:

“AAAAA 1x1”, “AAAAA 1x2”, “BBBBB 1x1”, “BBBBB 1x2”, “CCCCC 1x1”, “CCCCC 1x2”.

And in folder “B”, I have the following folders:

“AAAAA”, “BBBBB”, “CCCCC”.

What I’d like to do is move all the “AAAAA” files in folder “A”, to folder “AAAAA” in folder “B”, “BBBBB” files to folder “BBBBB”, and so on.

How would I do this using Apple Script?

Thanks.

set source to (path to desktop folder as text) & "A:"
set destination to (path to desktop folder as text) & "B:"
tell application "System Events"
	set lesNoms_theNames to name of files of folder source whose visible is true
end tell
repeat with unNom_aName in lesNoms_theNames
	set clef_key to text 1 thru 5 of unNom_aName
	if clef_key is in {"AAAAA", "BBBBB", "CCCCC"} then
		
		set orig to quoted form of POSIX path of (source & unNom_aName)
		set target to quoted form of POSIX path of (destination & clef_key)
		do shell script "mv " & orig & space & target
	end if
end repeat

is supposed to do the job.

Yvan KOENIG (VALLAURIS, France) dimanche 3 novembre 2013 18:39:04

Hi,

try this, sourceFolder is folder A, destinationFolder is folder B


set sourceFolder to choose folder
set destinationFolder to choose folder
tell application "Finder"
	repeat with aFolder in (get folders of destinationFolder)
		set folderName to name of aFolder
		set filesToMove to (files of sourceFolder whose name begins with folderName)
		move filesToMove to (contents of aFolder)
	end repeat
end tell


Thank you both for your input. :slight_smile:

I’ve been trying to set a custom path manually instead of having a “choose folder” prompt. I’ve tried so many different ways, but none work. How do I do that?


set sourceFolder to "/Users/JPCanaverde/Documents/A"


set sourceFolder to "SSD:Users:JPCanaverde:Documents:A"

None of these work. What am I doing wrong?

you need an alias specifier


set sourceFolder to alias "SSD:Users:JPCanaverde:Documents:A"

or, more portable


set sourceFolder to alias ((path to documents folder as text) & "A")

Thanks, it works! :smiley:

So here’s the final code that I’ll be using:


set sourceFolder to alias "SSD:Users:JPCanaverde:Documents:A"
set destinationFolder to alias "SSD:Users:JPCanaverde:Documents:B"
tell application "Finder"
	repeat with aFolder in (get folders of destinationFolder)
		set folderName to name of aFolder
		set filesToMove to (files of sourceFolder whose name begins with folderName)
		move filesToMove to (contents of aFolder)
	end repeat
end tell

Thanks again for everything. :slight_smile: