2
votes

Basically, I'm trying to create a folder action in Automator so whenever a file is added to a specific folder, it will create a subfolder that matches the filename (without the extension), then move the file into that subfolder.

So far, I have successfully used a post from this site (Create new folder named with a specified file name in Automator) to create a script that will create the new folder. However, I have been unable to modify the script to move the original file into the new folder.

Any help would be appreciated. Here is the full script I am working with for reference:

    on run {input, parameters} -- make new folders from base file names

    set output to {}

    repeat with anItem in the input -- step through each item in the input

        set anItem to anItem as text
        tell application "System Events" to tell disk item anItem
            set theContainer to path of container
            set {theName, theExtension} to {name, name extension}
        end tell
        if theExtension is in {missing value, ""} then
            set theExtension to ""
        else
            set theExtension to "." & theExtension
        end if
        set theName to text 1 thru -((count theExtension) + 1) of theName -- the name part

        tell application "Finder"
            make new folder at folder theContainer with properties {name:theName}
            set end of output to result as alias
        end tell
    end repeat

    return input -- or output
end run

Thanks in advance!

1

1 Answers

3
votes

Add this folder action to your target folder:

on adding folder items to theFolder after receiving theFiles
    repeat with aFile in theFiles
        tell application "System Events" to set {Nm, Ex, pPath} to aFile's {name, name extension, POSIX path of container}
        set BN to text 1 thru ((get offset of "." & Ex in Nm) - 1) of Nm
        set thePath to (pPath & "/" & BN & "/" as text)
        do shell script "mkdir -p " & quoted form of thePath
        delay 0.5
        tell application "Finder" to move aFile to POSIX file thePath
    end repeat
end adding folder items to