在AppleScript中查找和替换

时间:2015-01-23 17:08:54

标签: replace applescript

我目前正在编写一个超级简单的脚本,我需要在变量中找到并替换文本(特别是在掉到AppleScript上的项目的路径中。)这就是我目前所拥有的:

    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

(不包括不相关的代码并添加对话框以验证其是否有效)

那个“on replaceText ...”块我从搜索Stack Overflow获得了这篇文章的标题。我的问题是,当我尝试编译它时告诉我它预期“结束”但发现“开启”。我假设它要我在“替换文本”之前结束我的开放,但我不想这样做。关于如何让它发挥作用的任何想法?很抱歉,如果这很简单,我对AppleScript很新。

我知道我可以删除前12个字符然后将“/ ifs / disk1”添加到字符串的开头但我想知道为什么这不起作用以防再次发生。

2 个答案:

答案 0 :(得分:6)

您不能将处理程序放在另一个(显式)处理程序中。做了一些其他更正。

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

答案 1 :(得分:0)

您可以按照https://github.com/abbeycode/AppleScripts/blob/master/Scripts/Libraries/Strings.applescript

进行操作
on replace_text(this_text, search_string, replacement_string)
    set prevTIDs to AppleScript's text item delimiters
    set AppleScript's text item delimiters to the search_string
    set the item_list to every text item of this_text
    set AppleScript's text item delimiters to the replacement_string
    set this_text to the item_list as string
    set AppleScript's text item delimiters to prevTIDs
    return this_text
end replace_text