Applescript to move files based on filename

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

  1. macrumors newbie

    Joined:
    Oct 8, 2009
    #1
    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. macrumors 65816

    mysterytramp

    Joined:
    Jul 17, 2008
    Location:
    Maryland
    #2
    This is very basic, but it should get you started:

    Code:
    -- 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
    
    
    
    mt
     
  3. thread starter macrumors newbie

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

Share This Page