find, copy, and replace within filename

I’m trying to use folder actions on a mac to get the folder to execute the following algorithm whenever a file is dropped into it:

  1. if there’s no subfolder named CMYK, create one
  2. replace a bit of text in the file name with another bit

That’s pretty much it. I’ve been looking through tutorials, but I’ve never done this so I’m not even sure where to start. Can you give me any hints, or point me at a good online resource?

Example: i will have a folder on the Desktop called “ProjectNine” into which i will copy tif files named like “w*.sel8.1.tif" and i’d like to simply copy this file and rename it to "w*.cmyk.1.tif” and put it in a subfolder of called “cmyk”. I’d like this to happen automatically whenever a file is added to the folder (if its name contains sel8). “sel8” is persistent so i just need to do a find and replace of that to cmyk. my folder would look like this:

ProjectNine/
w1_1.sel8.1.tif
cmyk/
w1_1.cmyk.1.tif

It seems like it should be easy but I banging my head at this point. it would be a bonus if “cymk” was automatically created if it went missing.

Thank you for your help!

/ t

Let me get you started with this for changing names. You can’t change the name of the file while it’s in the folder with the action because that will trigger the action again. First, you move the file as is to the target folder, and then you change it’s name. In the Finder, name includes the extension, so everything but the text to be replaced is left as it was. I don’t know enough about your situation to know whether you’ll have to check that the name doesn’t already exist in the target folder and do something about duplicate names. To get some more help, you’ll have to post some code that is troubling you.

on findAndReplace(toFind, replaceWith, theText) -- Nigel Garvey
	set astid to AppleScript's text item delimiters
	set AppleScript's text item delimiters to toFind
	set textItems to theText's text items
	set AppleScript's text item delimiters to replaceWith
	tell textItems to set editedText to beginning & replaceWith & rest
	set AppleScript's text item delimiters to astid
	return editedText
end findAndReplace

set oldText to "sel8"
set newText to "cmyk"
set tName to "w432.sel8.1.tif"

set NewName to findAndReplace(oldText, newText, tName) --> "w432.cmyk.1.tif"