Applescript rename files

Discussion in 'Mac Programming' started by wesg, Nov 1, 2008.

  1. wesg macrumors regular


    Jan 2, 2008
    Toronto, ON
    This seems like a rather easy task, but I've searched with Google through this forum and others, and have yet to find a solution.

    I want to rename the files I've selected in Finder, and have successfully found the replacement text, but no matter what I do, i can't make applescript rename the file. I've gotten the POSIX path, and use the text
    set name of pathItem to renameFile
    to do the renaming, but I get nothing. Do I need to include the path and extension? In this case, pathItem is the path to the file, as in Macintosh HD/Users/.../Desktop/... and renameFile is exactly the same, except for the new name.

    What can I do differently?
  2. mysterytramp macrumors 65816


    Jul 17, 2008
    Your problem is probably in that you're not telling the Finder to do what you need done, as a result, Applescript's own file management dictionary is being used, which cannot rename files. This works, though it could be trimmed significantly:

    tell application "Finder"
    	set fileAlias to (choose file)
    	set filePath to fileAlias as text
    	set TID to AppleScript's text item delimiters
    	set AppleScript's text item delimiters to ":"
    	set fileName to last text item of filePath
    	set AppleScript's text item delimiters to "."
    	set fileNamePart1 to text item 1 of fileName
    	set fileNamePart2 to text item 2 of fileName
    	set fileName to fileNamePart1 & "001" & "." & fileNamePart2
    	set AppleScript's text item delimiters to TID
    	set name of fileAlias to fileName
    end tell
    Last line also works as:

    	set properties of fileAlias to {name:fileName}

Share This Page