Search code examples
applescriptautomator

Automator (2.5) Script to create folder based on file name and move file to folder


Thank you for taking the time to look. I am trying to create a workflow using automator 2.5 that will read the video files in my directory, create a folder with the file name, and move the file into the newly created folder. I have tried multiple scripts available online and encountered errors. Then I created this hybrid script which does not error or do anything. any assistance would be appreciated (I am not new to programming but inexperience with this version of automator) Screenshot of script


Solution

  • With your files selected in the front Finder window, running this following code in Script Editor.app should accomplish what you're looking to achieve

    tell application "Finder"
        activate
        set selectedFiles to selection as alias list
        set containingFolder to container of (item 1 of selectedFiles) --as alias
        repeat with i from 1 to count of selectedFiles
            set foldersRef to (a reference to folders of containingFolder)
            set foldersRefItems to name of (contents of foldersRef)
            set thisItem to item i of selectedFiles
            set fileName to (text items 1 thru -5) of (name of thisItem as text) as string
            if fileName is not in foldersRefItems then
                move thisItem to (make new folder at containingFolder ¬
                    with properties {name:fileName})
            else
                move thisItem to folder fileName of containingFolder
            end if
        end repeat
    end tell