I’m trying to create an AppleScript that filter certain files into different folders

applescript

I have various files / types, usually labelled in this kind of way:

000_160905_Iceman_Rumble_BA.jpg

There will be a variety of jpegs, PSD's, models etc and I need to find an automated way to file them away into various folders by date in some instances, by file types in other instances and by the initial of someone (BA).

Is there a way in AppleScript, where you can select certain characters from a file type (e.g the date in the file above), to automatically sync to another folder of my choice?

If anyone could help me here it would really save me!

Thanks

Best Answer

Here are some scripts that will help you. They are based on having some file selected in the Finder. The first one looks at each file, one at a time, and if the file's extension is jpg or png or gif, the file is moved to the Pictures folder.

tell application "Finder"
    set folder_one to path to desktop
    set folder_two to path to pictures folder
    set the_files to the selection
    repeat with a_file in the_files
        if name extension of a_file is in {"jpg", "png", "gif"} then
            move a_file to folder_two
        end if
    end repeat
end tell

The second script finds the last two characters before the extension, as in your "BA" at the end of your example file's name. Files are moved based on those last two characters. The script is not as tightly written as it could be but I wanted you to be able to read it and understand what is going on.

tell application "Finder"
    set folder_one to path to desktop
    set folder_two to path to pictures folder
    set the_files to the selection
    repeat with a_file in the_files
        set the_name to name of a_file
        set the_extension to name extension of a_file
        set the_extension_length to count of characters of the_extension
        set the_extension_length to the_extension_length + 1 -- for the dot
        set the_short_name_length to (count of characters of the_name) - the_extension_length
        set the_short_name to characters 1 thru the_short_name_length of the_name as string
        -- Now we have "just the name" (no dot, no extension)
        set the_last_two_characters to characters -2 thru -1 of the_short_name as string
        -- do stuff here, based on what those last two characters are
        if the_last_two_characters = "AB" then
            move a_file to folder_one
        end if
        --
        if the_last_two_characters = "XY" then
            move a_file to folder_two
        end if
    end repeat
end tell

Those scripts will get you started. You can use scripts like this with Hazel, as mentioned by tubedogg earlier, to file items as they are added to a folder.