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

时间:2015-02-26 19:24:34

标签: 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 Mavericks(10.9.4)

2 个答案:

答案 0 :(得分:0)

如果您只对改变" / 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:///

答案 1 :(得分:0)

如果您告诉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的“选择文件”或“选择文件夹”命令从任何文件或文件夹创建文件路径,该命令会提示用户使用对话框,使用户可以分别选择文件或文件夹。

相关问题