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

Trying to find and replace text in clipboard using applescript

我正在尝试将文件路径复制到剪贴板并将单词 "Volumes" 替换为 "MyServer"。目前我可以获得路径并替换空格,效果很好。现在我只需要替换那个词 "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 the clipboard to "afp://" & POSIX path of sel

end tell

OS X 小牛队 (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 的“选择文件”或“选择文件夹”命令从任何文件或文件夹创建文件路径,这会提示用户对话框,使他们能够分别选择文件或文件夹。