正在尝试使用appescription查找和替换剪贴板中的文本



我正在尝试将文件路径复制到剪贴板,并将单词"Volumes"替换为"MyServer"。目前,我可以获得路径并替换空间,这运行良好。现在我只需要替换"卷"这个词,我运气不好。这是我目前拥有的代码。任何帮助都会很棒。

tell application "Finder"
  set sel to the selection as text
  set TempTID to AppleScript's text item delimiters
  set AppleScript's text item delimiters to space
  set sel to text items of sel
  set AppleScript's text item delimiters to "%20"
  set sel to sel as string
  set AppleScript's text item delimiters to TempTID
  set the clipboard to "afp://" & POSIX path of sel
end tell

OS X Mavericks(10.9.4)

如果你只对更改路径开头的"/Volumes/"感兴趣,你可以这样做(如果路径不符合标准,就不使用它):

tell application "Finder"
    set sel to the selection as text
    set TempTID to AppleScript's text item delimiters
    set AppleScript's text item delimiters to space
    set sel to text items of sel
    set AppleScript's text item delimiters to "%20"
    set sel to sel as string
    set AppleScript's text item delimiters to TempTID
    set posixSel to POSIX path of sel
    if posixSel starts with "/Volumes/" then
        set posixSel to ("/MyServer" & (text 9 thru end of posixSel))
    end if
    set the clipboard to "afp:/" & posixSel
end tell
--I changed to afp:/ instead of afp:// because I think you need afp:// not afp:///

如果你告诉像TextWrangler这样的文本编辑应用程序(在Mac app Store上免费)代替Finder来做这项工作,你可以编写一个更简单、更易于维护的脚本:

tell application "TextWrangler"
    set theClipboardContents to the clipboard as text
    set theNewClipboardContents to replace "Volumes" using "MyServer" searchingString theClipboardContents
    set the clipboard to theNewClipboardContents
end tell

上述脚本也适用于TextWrangler的老大哥BBEdit。

理想情况下,在编写脚本的每一部分时,您都会针对该功能选择最合适的应用程序。该功能在应用程序中,而不是在AppleScript中,AppleScript是一种几乎没有内置功能的"小语言"。因此,就像打开文本编辑器编辑文本一样,脚本应该告诉文本编辑器在编辑文本时要承担繁重的工作。类似地,当您的脚本想要处理磁盘、文件夹和文件时,应该告诉Finder完成繁重的工作。

此外,避免使用AppleScript的文本项分隔符可以延长您的寿命。

您可以使用AppleScript的"选择文件"或"选择文件夹"命令从任何文件或文件夹创建文件路径,这些命令会提示用户使用对话框,使他们能够分别选择文件或文件夹。

最新更新