OmnicronCS
OmnicronCS

Reputation: 41

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

Upvotes: 0

Views: 2537

Answers (2)

mtomsic
mtomsic

Reputation: 1

This script works regardless of the file extension length. It also only works on files, so it is possible to select everything inside some directory and none of the folders will be affected.

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

Upvotes: 0

wch1zpink
wch1zpink

Reputation: 3142

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

Upvotes: 3

Related Questions