Applescript to move files based on filename

Discussion in 'Mac Programming' started by jdavis71, Oct 8, 2009.

  1. jdavis71 macrumors newbie

    Oct 8, 2009
    Hello, I am looking for an AppleScript that will move files based on the name of the file.

    For example, a file named "johndoe-report1" would be moved to the network drop box for the user "johndoe".

    This is for teachers to return graded work to students with minimal effort using a folder action.

    Thanks for any input!
  2. mysterytramp macrumors 65816


    Jul 17, 2008
    This is very basic, but it should get you started:

    -- extractFileName expects a string "firstpart-secondpart"
    -- text item delimiters set to "-" so it can extract
    -- firstpart from secondpart and returns firstpart
    on extractFirstName(fileName)
    	set TID to AppleScript's text item delimiters
    	set AppleScript's text item delimiters to "-"
    	set returnName to text item 1 of fileName
    	set AppleScript's text item delimiters to TID
    	return returnName
    end extractFirstName
    -- in your case you'd be better off with a line like:
    -- set dropBox to "hard drive:folder:folder:folder:"
    on open filez -- filez will be a list of aliases
    	set dropBox to (choose folder with prompt "Where should files go?") as string -- this works better for this test
    	tell application "Finder"
    		repeat with fa in filez -- fn is an alias
    			set fn to name of fa -- textual name of file
    			set source to quoted form of POSIX path of fa as string -- mv needs file path in POSIX form
    			set whoBelongs to my extractFirstName(fn)
    			set destination to quoted form of POSIX path of (dropBox & whoBelongs & ":")
    			do shell script "mv -f " & source & " " & destination -- this asks Unix to move the file
    			-- It's important to note that this script does not attempt
    			-- to catch fundamental errors. New files will overwrite
    			-- old files with the same name.
    		end repeat
    	end tell
    end open
  3. jdavis71 thread starter macrumors newbie

    Oct 8, 2009
    Thanks for the info!! I will give this a try today.

Share This Page