如何使用 AppleScript 在 POSIX 路径中使用变量?

How to use a variable in a POSIX Path with AppleScript?

我一直在尝试用变量替换 POSIX 路径中的一个部分,但我没有成功。这是我正在尝试开发的脚本:

tell application "Finder"
    duplicate POSIX file "/Users/**Variable**/Documents/img.jpg" to POSIX file "/Users/**Variable**/Desktop/" with replacing
end tell

路径中的部分是我希望变量出现的地方。我该怎么做?

你用 & 和变量分隔字符串。

此外,在编写 Finder 脚本之前将 posix 路径转换为 ​​Mac 标准冒号:路径是一种很好的做法。从 10.9 开始,Finder 的重复功能在这些方面就存在问题。 我已经分解了一些强制转换,所以你可以看到发生了什么。

-- define file and user names
set fileName to "img.jpg"
set user1 to "Mitc"
set user2 to "Mitc"

-- create posix path strings
set path1 to "/Users/" & user1 & "/Documents/" & fileName
set path2 to "/Users/" & user2 & "/Desktop/"

-- convert posix paths into colon paths
set ref1 to (POSIX file path1) as string
set ref2 to (POSIX file path2) as string

-- display dialog ref1 & return & ref2 -- to test
tell application "Finder" to duplicate alias ref1 to alias ref2 with replacing

您必须使用 " & 告诉脚本停止读取目录并添加变量,结果如下:

tell application "Finder"
     duplicate POSIX file "/Users/" & variable & "/Documents/img.jpg" to POSIX file "/Users/" & variable & "/Desktop/" with replacing
end tell

(确保使用 "set" 命令生成变量,EG。)

set variable to "text"

希望对您有所帮助!