AppleScript - 如何将文本附加到文件末尾

AppleScript - How to append text to end of a file

我想要一个我可以 运行 的脚本,它基本上采用我在 finder 中选择的 .rdp 文件,并在其末尾附加一行文本。

例如

我下载了一个 .rdp 文件以在 Microsoft Remote Access 中使用并加快我的工作流程我想在启动它之前在末尾附加文本 'Use Multimon:i:1' 这样我就没有每次打开首选项。

我对 AppleScript 不是很熟悉,所以如果有任何关于如何实现这一点的建议,我将不胜感激。

谢谢!

这目前适用于扩展名为 'txt' 的选定文件。对其进行测试,如果它适合您,请将其编辑为您想要的扩展名。

'if' 语句是为了确保您不会不小心将文本附加到可能损坏该文件的二进制文件中。 'return' 表示您的文本将单独显示一行。如果您不想这样,请删除 'return & '。 'open for access'详情请见Language Guide: Commands Reference。在同一页面上,您可以找到 'close access'.

tell application "Finder"
    set tFile to selection as alias
    
    if name extension of tFile is "txt" then
        set corR to true
    else
        display alert "Are you sure you've selected the correct file?"
        set corR to false
    end if
end tell

if corR is true then
    set ab to open for access tFile with write permission
    write return & "Use Multimon:i:1" to ab starting at eof
    close access ab
end if

据我了解,.RDP 文件以纯文本格式保存。如果是这种情况,在 AppleScript 中使用 do shell script 命令,将文本附加到文件就相当简单了。以下 AppleScript 代码应该适合您。

将以下代码粘贴到新的脚本 Editor.app 文档中。然后 使用当前在 Finder 中选择的 .RDP 文件,运行 脚本 Editor.app 中的代码,它会将文本附加到您的文件中。

property addText : "Use Multimon:i:1"

tell application "Finder" to set selectedFile to POSIX path of ((get selection) as alias)

do shell script "echo " & quoted form of addText & " >> " & quoted form of selectedFile