I’m trying to write a script that moves files into a group of folders depending on the last part of the filename (not just the file extension). For example a list of files might be:-
aa2_ck206D.eps
aa2_ck206S.eps
aa2_ck206T.eps
I want move the files from the one they’re in into one of three folders:-
D
S
T
This part of the filename is the 5th character from the left, how can I select that part of the filename so I can move it into the appropriate folder?
property s_Folder : “start” – path to sourcefolder
property d_folder : “end” – path to destinationfolder
tell application “Finder” to set file_list to every file of folder s_Folder – reads all files in the sourcefolder
repeat with one_file in file_list – repeats with one file from the sourcefolder
tell application “Finder” to set one_file_name to name of (contents of one_file) – get the name of the file
set name_of_folder to item -5 of one_file_name – get the character for the foldername
try
tell application “Finder” to make new folder in folder d_folder with properties {name:name_of_folder} – creates a new folder if not exist
end try
tell application “Finder” to move file one_file_name of folder s_Folder to folder name_of_folder of folder d_folder with replacing – move the files to the right folder and overwrites existing files with the same name
end repeat
Thanks for that Roland, it works beautifully. There is one slight hitch in that for every file in the original list I get an ‘untitled folder’ created even if the required folder exists i.e. S,D,T. Apart from that though all the files are sorted into the relevant folders as required, all I do is delete the ‘untitled’ folders.
I’ve had another look at the script but with my limited knowledge of Applecsript can’t understand why I get the ‘untitled’ folders.
tell application “Finder” to set file_list to every file of folder s_Folder
repeat with one_file in file_list
tell application “Finder” to set one_file_name to name of (contents of one_file)
set name_of_folder to item -5 of one_file_name
tell application “Finder”
if not (exists folder name_of_folder of folder d_folder) then
make new folder in folder d_folder with properties {name:name_of_folder}
move file one_file_name of folder s_Folder to folder name_of_folder of folder d_folder with replacing
else
move file one_file_name of folder s_Folder to folder name_of_folder of folder d_folder with replacing
end if
end tell
end repeat