如何使用AppleScript或Shell脚本在OSX中获取文件URL?

pat*_*ick 2 url macos shell applescript finder

我尝试一起破解Keyboard Maestro快捷方式,以便为我提供文件的URL(就像“路径查找器”的输出一样)。

到目前为止,我用下面的AppleScript和替代空间%20

tell application "Finder"
    set sel to the selection as text
    set the clipboard to POSIX path of sel
end tell
Run Code Online (Sandbox Code Playgroud)

然后我简单地追加file://localhost/

问题是涉及特殊字符时,例如,我在桌面上有以下文件夹:

我的输出: file://localhost//Users/patte/Desktop/#%20Old%20files

正确的输出应转换哈希值: file://localhost/Users/patte/Desktop/%23%20Old%20files


使用AppleScript或Shell脚本的解决方案将是很棒的,因为我有能力将其合并。我也尝试过,set the clipboard to URL of the first item of (get the selection)但这对我没有用-也许我做错了。

另一个选择是对特殊字符进行编码的脚本-我也可以使用该脚本,但是我不确定将什么转换成什么-否则我会寻找它。

小智 5

这是一个简单的AppleScript,它将循环搜索Finder选择并将文件URL以返回分隔的字符串形式放置在剪贴板上。它使用mklement的“两行”代码,可与Keyboard Maestro一起使用:

set theOutput to ""

-- Obtain Finder selection and store it in variable "sel".
tell application "Finder" to set sel to get selection as alias list

repeat with x in sel

-- Convert to alias, then determine its file URL and store that in variable "myFileUrl"
tell application "System Events" to set myFileUrl to URL of x

if theOutput = "" then
    set theOutput to myFileUrl
else
    set theOutput to theOutput & return & myFileUrl
end if

end repeat

set the clipboard to theOutput
Run Code Online (Sandbox Code Playgroud)