如何以编程方式将多个文件复制到macOS的剪贴板?


1

我最终想要一个bash函数 to-clipboard 获取文件路径并将文件复制到剪贴板。使用其他脚本语言作为帮助是可以的。我目前有这个用于复制单个文件:

file-to-clipboard() {
    osascript \
        -e 'on run args' \
        -e 'set the clipboard to POSIX file (first item of args)' \
        -e end \
        "$@"
}

据说这个Applescript可以复制多个文件,但我根本不喜欢它:

set f to {(POSIX file "/path/to/a/folder/a.png"), (POSIX file "/path/to/another/folder/b.png")}
tell application "Finder"
    try -- to delete any old temp folder
        delete folder "AS_mailCopy" of (path to temporary items)
    end try
    set tmp to make new folder at (path to temporary items) with properties {name:"AS_mailCopy"}
    duplicate f to tmp
    select files of tmp
    activate
    tell application "System Events" to keystroke "c" using command down
    delete tmp
end tell

相关问题:

使用applescript将文件复制到剪贴板


你能解释一下你在bash提示符下输入的内容,以及之后剪贴板应包含的内容吗? (我不清楚你是否想要剪贴板中的文件路径,或文件的内容等...)另外,你看过命令吗? pbcopy
Ashley

Answers:


3

您可以使用下面的AppleScript创建一个bash函数,通过将其文件路径作为命令行参数提供,可以将多个文件对象添加到剪贴板。它回来了 true 成功和 false 失败了。

您将无法将项目粘贴到终端内,但如果您导航到某个位置 发现者 ,你可以粘贴那里的项目。我希望这与你所追求的一致。

use framework "Appkit"
use Finder : application "Finder"

property this : a reference to current application
property NSFileManager : a reference to NSFileManager of this
property NSImage : a reference to NSImage of this
property NSMutableArray : a reference to NSMutableArray of this
property NSPasteboard : a reference to NSPasteboard of this
property NSString : a reference to NSString of this
property NSURL : a reference to NSURL of this

property pb : missing value

on run input
    if input's class = script then set input to ¬
        Finder's selection as alias list

    init()
    clearClipboard()
    addToClipboard(input)
end run


to init()
    set pb to NSPasteboard's generalPasteboard()
end init

to clearClipboard()
    if pb = missing value then init()
    pb's clearContents()
end clearClipboard

to addToClipboard(fs)
    local fs

    set fURLs to NSMutableArray's array()
    set FileManager to NSFileManager's defaultManager()

    repeat with f in fs
        if f's class = alias then set f to f's POSIX path
        set fp to (NSString's stringWithString:f)'s ¬
            stringByStandardizingPath()
        if (FileManager's fileExistsAtPath:fp) then ¬
            (fURLs's addObject:(NSURL's fileURLWithPath:fp))
    end repeat

    if pb = missing value then init()
    pb's writeObjects:fURLs
end addToClipboard

我建议将此脚本保存为 .applescript 要么 .scpt 使用的文件在您的计算机上的某处 脚本编辑器 。然后,在您的终端中,创建您的bash功能:

pbadd() {
    osascript "/Path/To/Saved AppleScript.scpt" "$@"
}

然后,使用:

pbadd ~/Pictures/*.jpg
pbadd ~/Documents/Some\ file.pdf ~/Music/A\ Random\ Song.mp3
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.