How to move files to folders based on name of file using AppleScript

Hi,

I am rather new to AppleScript and am trying to accomplish the following as a teacher.


On my Macbook I correct a large number of student documents which are saved by students with the name of the document and then _NameLastname, for example "Creative writing_SteveJobs".


I am trying to write an Applescript so that when my downloads folder receives such a file it automatically runs the script and then moves said file to a folder I have with the student's name for example "Steve Jobs" (located at "/Users/XXX/Desktop/Steve Jobs").


I have tried looking around online and I have tried to use automator. The things I found online did not work properly and when I tried to test it using automator (I was using files and folders such as "_A", "_B" and "_C" to represent student's names. In this case it just moved all the files into the folder marked "_A" even though I had created separate commands within automator for said folders and files.


Is there anyone who can help with the applescript please?


Thanks!

MacBook Pro, iOS 11.4.1

Posted on Aug 5, 2018 11:56 AM

Reply

Similar questions

19 replies

Aug 7, 2018 5:46 AM in response to DMLaMiranda

Sorry for the delay, but I chose to rewrite parts of the AppleScript (and Ruby) for efficiency, and to better validate the dropped files. And last evening, storms took out my Internet. Student folders are now created in Desktop : Students, and respective, valid files are moved from the drop folder to the student folders.


I have tested it on the following filename formats with color coded result. [1,2] Green success. [3,4] Red error dialog.

  1. Student_report_SteveJobs.docx
  2. This weeks report_HavisMedwic.xls
  3. My daily report_for_you.xls
  4. Here is a report_for_you.docx


Open Automator, and from the File menu : Open Recents, and choose your folder action from yesterday. Once opened, select all of the content in the Run AppleScript action and backspace to remove. You should have a blank action. Now, copy/paste all of the following AppleScript code into that Run AppleScript action window, and click the hammer icon to compile it. Save the folder action. No need to change the name, this will just update it.


Code:


-- Folder Action to inspect dropped files against a specified filename format and then extract

-- student name from the filename to create named folders under Desktop : Students folder. Then

-- move the dropped filename into the respective students folder. Base filename must end in "_FirstLast".

-- Version: 1.5

-- VikingOSX, 2018-08-06, Apple Support Communities, No warranties or service expressed or implied.

use scripting additions

property fStudents : "Students:"

property outpath : ((path to desktop as text) & fStudents) as alias

property delim : "_"


on run {input, parameters}

repeat with anItem in input

tell application "Finder" to set workStr to name of anItem

set theArgs to workStr'squoted form & space & delim'squoted form

set studentFolder to my validate_filename(theArgs) as text


if studentFolder is "false" or studentFolder is "" then

display dialog "Invalid file format" & return & return & workStr & return & return & "Processing ends." with icon stop giving up after 15

exit repeat

end if


try

set outfolder to (outpath & studentFolder & ":") as alias

on error

set outfolder to (outpath & studentFolder & ":") as text

tell application "Finder" to makenewfolderatoutpathwith properties {name:studentFolder}

end try

tell application "Finder" to move anItem to folder outfolder

end repeat

return input

end run


on validate_filename(sargv)

return do shell script "ruby <<'EOF' - " & sargv & "

#!/usr/bin/ruby


sname, delim = ARGV

# regular expression to match against filename format

xr = /(.*?)(_[A-Z].*[A-Z].*)\\.(.*?)\\z/

valid = xr.match(sname) # no match implies nil result

puts !valid.nil? ? sname.split(/(?=[ A-Z#{delim}.])/)[-3..-2].insert(1, ' ').join : false

EOF"

end validate_filename

Aug 6, 2018 8:42 AM in response to DMLaMiranda

I had a working folder action last evening, but wanted to refine it further, so that it flagged filenames that did not conform to the "_FirstLast" suffix. It now performs this correctly, and really doesn't care what the filename formatting is prior to that specified suffix, or the document extension either. If the filename does not match the format, it remains in the drop folder, otherwise, it is moved to the students "First Last" folder on the Desktop. The script will check if the students folder exists, and if not, will create it.


Example of encountering invalid filename format:

User uploaded file


This will be an Automator Folder Action that uses a single, Run AppleScript action. You copy/paste the AppleScript source that I provide below into that action, select the drop folder, and save. When you save the Folder Action, it will be written into your local Library:Workflows:Applications:Folder Actions location — and immediately ready to use.


Launch Automator

  1. Dock : Launchpad : Other : Automator
    1. New Document
      1. Select Folder Action
      2. Choose
    2. Automator will launch to a three-panel screen. The libraries are on the left, and you want to select the Run AppleScript action, and then drag/drop it into the large, right-hand workflow window.
    3. Once dropped, it will look like this:
      User uploaded file
    4. Select all contents of the Run AppleScript and backspace to remove it.
    5. Copy/paste the AppleScript below, and paste into this same window. You can click, and drag the bottom of the window to enlarge it.
    6. Once you have pasted the AppleScript, click the symbolic hammer button, so that the AppleScript now becomes multi-colored.
    7. At the top of the workflow, you must set the designated drop folder that the Folder Action will use.
    8. Save the Folder action with a familiar name (e.g. process_students).
      1. Automator saves its Folder action in your local Library folder in Workflows:Applications:Folder Actions.
      2. The Folder Action is ready to use as soon as you save it from Automator.
    9. Quit Automator.


Code for step A5: (the following will not appear correctly unless you are signed into the community)


use scripting additions

property outpath : (path to desktop) as alias


on run {input, parameters}

set delim to "_"

repeat with anItem in input

tell application "Finder" to set workStr to name of anItem

set theArgs to workStr'squoted form & space & delim'squoted form

set studentFolder to my validate_filename(theArgs) as text


if studentFolder is "false" then

display dialog "Invalid File format" & return & return & workStr & return & return & "Processing ends." with icon stop giving up after 10

exit repeat

end if


try


-- check if the student folder exists yet

set outfolder to ((path to desktop) & studentFolder & ":") as alias

on error

set outfolder to ((path to desktop) & studentFolder & ":") as text

end try


tell application "Finder"


-- make new student folder if not present

if not (exists folder outfolder) is true then


makenewfolderatoutpathwith properties {name:studentFolder}

end if


moveanItemtofolderoutfolder

end tell

end repeat

return input

end run


on validate_filename(argv)

return do shell script "ruby <<'EOF' - " & argv & "

#!/usr/bin/ruby


# ensure filename is valid format and return student folder as 'First Last'

# if invalid format then return false

valid = ARGV.first.partition(ARGV.last).last.include?(ARGV.last)

puts valid ? ARGV.first.split(/(?=[A-Z#{ARGV.last}.])/)[-3..-2].insert(1, ' ').join : false

EOF"

end validate_filename

Aug 6, 2018 12:31 AM in response to DMLaMiranda

1. After placing the script in your user's ~/Library/Scripts/Folder Action Scripts folder, you can right-click on a folder and select the Folder Action Setup service. In the setup dialog, you can enable folder actions and add folders and the actions you want to run with them. The script can also be run directly from the Script Editor (for testing or manual operation or whatever).


2. In the run handler, the line where it is setting the destination property - in my example, this is being set to your user's Desktop folder. You can also run a small script such as:


set theFolder to (choose folder) as text
display dialog theFolder
set the clipboard to theFolder


...and then in my script set the path (although the script won't be as portable) by pasting the result into the line:


set my destination to "paste:path:here:" as alias


3. The student names are extracted from the file name (the text following the last delimiter character), so these folders would be previously created in the destination folder for the script. The names have regular spacing, such as "Steve Jobs", and the script will take a file with a name such as "SteveJobs" and split it on the capitalization. Note that although the script will handle files without a file extension, the macOS usually needs one so that it knows the format of the file.

Aug 6, 2018 11:27 AM in response to DMLaMiranda

I had some other time commitments in the last hour, so I will look at the sensible use of the Students folder off of your Desktop. Should be a minor change, but will still have to test again.


My assumption for filenaming is: any combination of characters_FirstLast.ext, and I the script is just working on the bold string to make the student's folder name. Let me look at the code again to make certain something is not slipping past. If that underscore is missing then error every time.


What filename string is still sitting in the drop folder after the error dialog? Can you provide that filename here using _FirstLast to anonymize the student name?

Aug 6, 2018 12:41 PM in response to DMLaMiranda

Did you create the Automator folder action that I described with the AppleScript code pasted inside the Run AppleScript. At the top of the Folder Action, you would be required to select the folder that the student reports would be either saved, or drag/dropped.


When the filename with the original naming convention that you stated is saved/dropped onto the drop folder, then the script will determine the students name, whether or not their folder exists, make it if necessary, and then move the file to the student's folder.


Your only input to the Automator Folder Action is the filenames that you save, or drag/drop onto the designated drop folder.

This thread has been closed by the system or the community team. You may vote for any posts you find helpful, or search the Community for additional answers.

How to move files to folders based on name of file using AppleScript

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.