views:

44

answers:

2

I was wondering if there was a way in Automator to use Applescript code to get the extension of a file, and if it equals a specific extension (e.g. .pdf or .rtf) move to a specific folder for that extension (e.g if (extension == pdf) { move to folder "~/PDF Files" } else if (extension == rtf) { move to folder "~/Rich Text Files" })

A: 

I'm not at my Apple right now, so I can't play around with Automator and figure it out. But if you could do this by switching finder to list view, sort by type, and then select blocks of files of the same type and drag them into the right folder.

Nathan
+2  A: 

Here's an applescript. Since your request was simple I just wrote it for you. Note how I get the file extension with the subroutine "getNameAndExtension(F)". Normally you can get the file extension from the Finder (called name extension) but I've found that the Finder is not always reliable so I always use that subroutine. That subroutine has always been reliable.

set homeFolder to path to home folder as text
set rtfFolderName to "Rich Text Files"
set pdfFolderName to "PDF Files"

-- choose the files
set theFiles to choose file with prompt "Choose RTF or PDF files to move into your home folder" with multiple selections allowed

-- make sure the folders exist
tell application "Finder"
    if not (exists folder (homeFolder & rtfFolderName)) then
        make new folder at folder homeFolder with properties {name:rtfFolderName}
    end if
    if not (exists folder (homeFolder & pdfFolderName)) then
        make new folder at folder homeFolder with properties {name:pdfFolderName}
    end if
end tell

-- move the files
repeat with aFile in theFiles
    set fileExtension to item 2 of getNameAndExtension(aFile)
    if fileExtension is "rtf" then
        tell application "Finder"
            move aFile to folder (homeFolder & rtfFolderName)
        end tell
    else if fileExtension is "pdf" then
        tell application "Finder"
            move aFile to folder (homeFolder & pdfFolderName)
        end tell
    end if
end repeat



(*=============== SUBROUTINES ===============*)
on getNameAndExtension(F)
    set F to F as Unicode text
    set {name:Nm, name extension:Ex} to info for file F without size
    if Ex is missing value then set Ex to ""
    if Ex is not "" then
        set Nm to text 1 thru ((count Nm) - (count Ex) - 1) of Nm
    end if
    return {Nm, Ex}
end getNameAndExtension
regulus6633