Batch create folders based on part of file name and move files into that folder - Mac - applescript

I need to create a folder based on the first part of the file and then move that file and all other files with that same first part of the file name into that folder. In this case the folder would be named "1234-City-Artist-1080x1920". The folder will always be named the same as the "city" part of the file up until the space. There will be multiple files with the same city that need to go in the same file, so I need to build a sequence that tells it to just move the folder in to the folder if it already exists.
I found this solution for windows:
Batch create folders based on part of file name and move files into that folder
I need the Mac equivalent to run AppleScript.
I've managed to figure out a script to make a folder for EVERY file in the folder I run ...
tell application "Finder"
      
      set selected to selection
      
       set current_folder to item 1 of selected
      
       set mlist to every file of current_folder
      
       repeat with this_file in mlist
             
              set cur_ext to name extension of this_file
             
              set new_name to text 1 thru -((length of cur_ext) + 2) of (name of this_file as text)
             
              set new_folder to make new folder with properties {name:new_name} at current_folder
             
              move this_file to new_folder
             
       end repeat
      
end tell
... now I need to figure out how to make using only a section (city) of the file name (1234-city-artist-size), AND put all files with the same (city) name in the same folder. I'm getting very lost when it comes to pulling just a section of the file name, and not getting an error when a folder has already been created.
Any thoughts on how to edit the script to make this work?

Related

Automatically move files of a certain type from folder A to B whenever they are added to folder A on macOS

Using Automator, I created a "Folder Action" to move files of certain types (i.e. "Kind IS Movie") from folder "FolderA" to folder "FolderB" as soon as they are added to folder "FolderA". It works fine except that it doesn't move files from subfolders (e.g. doesn't work if the movie files are added to "FolderA/SubA/"), and apparently there's no option on Automator to make it work on the subfolders.
Does anyone have any idea about how to either change that on Automator or how could I create a script for that? Thanks!
This following AppleScript folder action code should give you a general idea of how to accomplish what you are looking for. When a file or folder is added to a folder that this folder action is attached to, it will search all folders and sub folders for files (I used QuickTime movie as the kind of file... But you can change that to whatever you want) then those files will be moved to the folder that you will define in property moveToFolder
You can save this following code in Script Editor.app directly into your /Users/Your_User_Name/Library/Workflows/Applications/Folder Actions folder, as a .scpt file. Once the script is saved into that folder, it will be available to attach to any folder as a folder action using the Folder Actions Setup.
-- Set This To The Folder You Want Your Videos Moved To
property moveToFolder : (path to desktop as text) & "moved_videos"
-- Set This To The Kind Of File To Act Upon
property fileKind : "QuickTime movie"
on adding folder items to theFolder after receiving theNewItems
tell application "Finder"
set movieFilesRef to a reference to (files of entire contents of folder theFolder ¬
whose kind is fileKind)
move movieFilesRef to alias moveToFolder
end tell
end adding folder items to
OR Here Is A Version Which Defines The Name Extensions Of The Files To Act Upon
-- Set This To The Folder You Want Your Videos Moved To
property moveToFolder : (path to desktop as text) & "moved_videos"
-- Set This To The Name Extensions Of Files To Act Upon
property videoFileExtensions : {"m4v", "mkv", "avi", "mp4", "mov", "wmv", "mpg"}
on adding folder items to theFolder after receiving theNewItems
tell application "Finder"
set movieFilesRef to a reference to (files of entire contents of folder theFolder ¬
whose name extension is in videoFileExtensions)
move movieFilesRef to alias moveToFolder
end tell
end adding folder items to

AppleScript - Move all the files contained in subfolder to a top folder

I am looking for an edit to the current script. What I need is moving all the files from subfolders (recursively) in to one top folder, however if a file with the same name exist, create a new top-folder and continue there, this is what I have so far:
tell application "Finder"
try
set Random_name to random number from 100 to 9999
set theTopFolder to (choose folder)
set theFiles to a reference to every file of (entire contents of folder theTopFolder)
set theNewFolder to make new folder at theTopFolder with properties {name:"Flattened Files"}
move theFiles to theNewFolder
on error
set theNewFolder to make new folder at theTopFolder with properties {name:"Flattened Files" & Random_name}
move theFiles to theNewFolder
end try
end tell
Just to be clear the structure of the path is not:
Mainfolder/subfolder/file.xxx but Mainfolder/subfolder/sulbfolder2/subfolder3/....100/file.xxx so the script needs to work recursively which it does but it stops when a file exist with the same name
When a file with the same name exist my edit creates a new folder with Flattened Files+random number however when another file with the same name is moved the script stops for an error instead going ahead and creating a new Flattened Files+randonnumber folder. Any ideas?
Thank you
Your script isn't using recursion, it just lets the Finder get all the files. The additional error you are getting is because you are trying to move the whole list of files again.
One solution would be to step through the file items, testing for duplicates as you go, and make new folders as needed. The following script just moves duplicates to added folders (note that an error will still stop the script). I don't know how you are sorting the file list, so I included a line to uncomment to continue moving file items to the added folder.
set theTopFolder to (choose folder)
tell application "Finder"
set theNewFolder to make new folder at theTopFolder with properties {name:"Flattened Files"}
set theFiles to every file of (entire contents of folder theTopFolder) as alias list
repeat with aFile in theFiles
if file ((theNewFolder as text) & (name of aFile)) exists then -- use added folders for duplicates
set counter to 1
set done to false
repeat until done
set suffix to text -2 thru -1 of ("000000" & counter) -- leading zeros for sorting
set alternateFolder to (theTopFolder as text) & "Flattened Files" & space & suffix
tell me to (do shell script "mkdir -p " & quoted form of POSIX path of alternateFolder) -- make new folder as needed
if file (alternateFolder & ":" & (name of aFile)) exists then -- continue to next one
set counter to counter + 1
else
move aFile to folder alternateFolder
# set theNewFolder to folder alternateFolder -- uncomment to continue moving here after a duplicate
set done to true
end if
end repeat
else
move aFile to folder (theNewFolder as text)
end if
end repeat
end tell

AppleScript / FolderAction - Rename files when dropped in folder > Endless Loop

I am trying to do the following with a FolderAction and AppleScript:
Everytime I drop a file on a specific folder it should be renamed and then moved into another folder.
The problem is I get something like an infinite loop (I think) because when the file gets renamed the folder assumes that there is a new file in the folder and so on.
I really don't know how to avoid this and stop the endless loop. Here ist my script:
global newName
set newName to ""
on adding folder items to theAttachedFolder after receiving theNewItems
-- Get the name of the attached folder
tell application "Finder"
set theName to name of theAttachedFolder
-- Count the new items
set theCount to length of theNewItems
-- Display an alert indicating that the new items were received
activate
-- Loop through the newly detected items
repeat with anItem in theNewItems
set oldFileName to name of anItem
-- Rename the file
set the name of anItem to "NewFile" & oldFileName
-- Move the file to other folder
move anItem to "Macintosh HD:Users:blabla:blabla"
end repeat
end tell
tell application "Finder"
delete files of folder "Macintosh HD:Users:user:thisfolder
end tell
end adding folder items to
You are right, renaming the file triggers the folder action again.
The solution is to change the order: First move then rename.
-- Move the file to other folder
set movedItem to move anItem to "Macintosh HD:Users:blabla:blabla"
-- Rename the file
set the name of movedItem to "NewFile" & oldFileName

Applescript: Copy all contents of a folder into every folder in a directory

I'm in a bit of a bind and an Applescript noob. I've been stumbling through a script that would allow me to copy the contents of (TemplateFolder) into all of the client folders in a directory, with the added crux that all of the existing clients' folder contents be moved into a folder within the client labeled "Old Files" or something of the sort. I'll include images with my script thus far to illustrate what I'm trying to achieve. Thank you everyone in advance for all your help.
P.S. Since I don't have the rep required, I'll have to post links to my images.
http://imgur.com/a/lL9q7
The first image is the template folder (the folder I'd like all contents copied into each client folder).
The second image is an example of an existing client folder with all the bad structure (or lack thereof).
The final image is the expected results where the template folder's contents are moved into the client folder and the original content of the client's folder are moved into a separate folder titled "Old Structure Files".
Below is the applescript I've written, with help from others, to copy the contents. However there are missing components and some elements that need to change; currently the applescript simply copies the entire folder rather than just the contents and it makes a simple copy rather than inserting, the script is not recursive for an entire directory, and there's no function to move the existing client files into a "Old Structure Files" folder. Again, any and all help is greatly appreciated :)
on run
set source_folder to choose folder with prompt "Select folder to be duplicated:" as string
my do_main_script(source_folder)
end run
on open of source_folder_list
repeat with i from 1 to number of items in the source_folder_list
set this_folder_path to item i of the source_folder_list as string
if last character of this_folder_path is ":" then
my do_main_script(this_folder_path)
end if
end repeat
end open
on do_main_script(source_folder)
tell application "Finder" to set source_folder to folder (source_folder)
tell application "Finder" to set the target_folder to (parent of source_folder)
if source_folder is not "" and target_folder is not "" then
set new_folder_name to (name of source_folder as string) & " duplicate"
set source_folder to source_folder as string
set target_folder to target_folder as string
my create_new_folder(target_folder, new_folder_name)
my duplicate_folder_structure(source_folder, target_folder & new_folder_name & ":")
end if
end do_main_script
In the script bellow, the template folder is at fixed place on desktop, all the content of the customer selected folder is moved to a new folder "old structure", and after that, all content of the template folder is duplicated into the customer folder. If I well understand, this is what you're looking for :
set Templatefolder to "HD:Users:my_user:Desktop:Template"
set CustomerFolder to (choose folder with prompt "Select customer folder to be re-organised")
tell application "Finder"
set CustomerData to every item of CustomerFolder
set OldF to make new folder in CustomerFolder with properties {name:"Old Strutucture Files"}
move CustomerData to OldF
set Newstructure to every item of folder Templatefolder
duplicate Newstructure to CustomerFolder
end tell

Copying files in Finder with AppleScript

This is my first attempt at AppleScripting.
I have 3 folders that contain image files.
Test Folder 1 has 77 large, master files.
Test Folder 2 has 4 smaller files in a subfolder called ABC with the same name as files in Test Folder 1.
Test Folder 3 Contains an empty sub folder called ABC.
I want a script to check the file names in Test Folder 2 and copy the equivalent file names from Test Folder 1 to Test Folder 3 subfolder ABC
Here is what I have so far:
tell application "Finder"
set the_files to (files of folder "Macintosh HD:Users:Ronnie:Pictures:Test Folder 1:")
set the_file_names to (files of folder "Macintosh HD:Users:Ronnie:Pictures:Test Folder 2:ABC:")
set target_folder to ("Macintosh HD:Users:Ronnie:Pictures:Test Folder 3:ABC:")
if document files of the_file_names is equal to document files of the_files then duplicate the_files to target_folder
end tell
Currently it will copy all the files from Test Folder 1 so its seams that the "If" script does not work.
Can someone help?
Ronnie
This is one way to do it.
--this is my preference. I prefer to work with strings then coerce them to aliases
--"aliases" in the old AppleScript/Mac API sense, meaning special file/folder path data type
-- (this is what is returned when you use the choose file or choose folder commands, e.g.)
-- aliases can be coerced to and from strings
-- not to be confused with POSIX style paths which use "/" as separator, OR
-- Finder item objects, which are specific to the Finder ('file x of folder y of startup disk z' style)
set tf1 to "Macintosh HD:Users:Ronnie:Pictures:Test Folder 1:"
set tf2 to "Macintosh HD:Users:Ronnie:Pictures:Test Folder 2:ABC:"
set target_folder to "Macintosh HD:Users:Ronnie:Pictures:Test Folder 3:ABC:"
--above not needed in Finder tell block
tell application "Finder"
set fileNames to (name of files of alias tf1) --we get the names of the files here; "name" filters, so does "files"
set matchNames to (name of files of alias tf2) --and the names of the files we want to match in testing
repeat with thisName in fileNames --repeat loop is necessary for this
if thisName is in matchNames then
--notice the concatenating of folder and name to make new alias that gets copied
duplicate alias (tf1 & thisName) to alias target_folder
end if
end repeat
end tell

Resources