Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and Replace in AppleScript

I'm currently writing a super simple script and I need to find and replace text in a variable (specifically in the path of the items dropped onto the applescript.) Here is what I have currently:

    on open {dropped_items}
    tell application "Finder" to set filePathLong to the POSIX path of dropped_items as text


on replaceText(find, replace, subject)
    set prevTIDs to text item delimiters of AppleScript
    set text item delimiters of AppleScript to find
    set subject to text items of subject

    set text item delimiters of AppleScript to replace
    set subject to "" & subject
    set text item delimiters of AppleScript to prevTIDs

    return subject
end replaceText

get replaceText("/mpc/mayors1", "/ifs/disk1", filePathLong)




display dialog subject

end open

(excluding irrelevant code and adding a dialog to verify it worked)

That "on replaceText..." block I got from searching Stack Overflow for the title of this post. My problem is that when I try to compile it tells me it expected an "end" but found an "on." I'm assuming it wants me to end my open before I can "on replaceText" but I don't want to do that. Any ideas as to what I could do to get it to work? Sorry if this is very simple, I'm pretty new to AppleScript.

I understand I could just chop off the first twelve characters and then add "/ifs/disk1" to the beginning of the string but I want to know why this isn't working in case this happens again.

like image 943
JohnShafto Avatar asked Jan 23 '15 17:01

JohnShafto


1 Answers

You can't place a handler within another (explicit) handler. Made some other corrections as well.

on open dropped_items
    repeat with anItem in dropped_items
        set filePathLong to anItem's POSIX path
        set mySubject to replaceText("/mpc/mayors1", "/ifs/disk1", filePathLong)
        display dialog mySubject
    end repeat
end open


on replaceText(find, replace, subject)
    set prevTIDs to text item delimiters of AppleScript
    set text item delimiters of AppleScript to find
    set subject to text items of subject

    set text item delimiters of AppleScript to replace
    set subject to subject as text
    set text item delimiters of AppleScript to prevTIDs

    return subject
end replaceText
like image 123
adayzdone Avatar answered Oct 14 '22 13:10

adayzdone