调用副本&从终端粘贴命令

时间:2012-08-25 18:22:09

标签: macos bash shell terminal copy-paste

是否可以从bash脚本调用复制命令(就好像用户按下了 Cmd + C )?基本上我想编写一个我用全局热键运行的简单脚本,它应该从活动应用程序中取出当前选择,替换某些内容并粘贴结果。这可能吗?

到目前为止,我能提出的最好的方法是使用pbpastepbcopy,但如果可能,我希望自动化。

1 个答案:

答案 0 :(得分:1)

如果您只是尝试修改文字选择,则可以使用AppleScript。

osascript -e 'try
    set old to the clipboard
end try
try
    delay 0.3
    tell application "System Events" to keystroke "c" using command down
    delay 0.2
    set text item delimiters to linefeed
    set input to (paragraphs of (the clipboard as text)) as text
    set the clipboard to do shell script "shopt -u xpg_echo; echo -n " & quoted form of input & " | rev" without altering line endings
    tell application "System Events" to keystroke "v" using command down
    delay 0.05
end try
try
    set the clipboard to old
end try'

如果脚本使用具有除命令之外的其他修饰键的快捷方式运行,则第一个延迟用于释放修饰键。第二个延迟也可以减少到0.05,但长选择或例如Web视图通常需要更长的延迟。如果没有第三次延迟,the clipboard有时会在粘贴文本之前设置为old

the clipboard as textdo shell script默认情况下将行结尾转换为回车符。需要shopt -u xpg_echo,因为echo中的sh默认解释单引号内的反斜杠。如果输入超过getconf ARG_MAX个字节,则您无法使用echo并且必须将其写入临时文件或使用pbpaste

pbpastepbcopy默认情况下会在do shell script使用的环境中使用问号替换非ASCII字符您可以通过将LC_CTYPE设置为{{1}来阻止此问题}。

告诉系统事件单击菜单栏项目通常会更慢,并且它不适用于没有菜单栏或全屏窗口的应用程序。

另一种选择是创建Automator服务。但是在运行之前它们也有很小的延迟。在菜单栏上显示一次服务菜单之前,服务的快捷方式始终有效,这是一个错误。当最前面的应用程序没有菜单栏或服务菜单时,服务不可用。

相关问题