我如何才能管道输出的命令到我的剪贴板,并粘贴回来时,使用终端?例如:

cat file | clipboard

当前回答

基于之前的文章,我最终得到了以下轻量级的别名解决方案,可以添加到.bashrc:

if [ -n "$(type -P xclip)" ]
then
  alias xclip='xclip -selection clipboard'
  alias clipboard='if [ -p /dev/stdin ]; then xclip -in; fi; xclip -out'
fi

例子:

# Copy
$ date | clipboard
Sat Dec 29 14:12:57 PST 2018

# Paste
$ date
Sat Dec 29 14:12:57 PST 2018

# Chain
$ date | clipboard | wc
   1       6      29

其他回答

只是为了覆盖一个边缘情况:),因为问题标题问(至少现在)如何将命令的输出直接复制到剪贴板。

我经常发现,在命令已经执行并且我不想或不能再次执行之后,复制命令的输出是很有用的。

对于这个场景,我们可以使用gdm或类似的鼠标实用程序并使用鼠标进行选择。apt-get安装gdm,然后右键单击或Cntrl+Shift+c和Cntrl+Shift+v组合在终端进行复制和粘贴

Or, which is the preferred method for me (as the mouse cannot select properly inside one pane when you have multiple panes side by side and you need to select more than one line), using tmux we can copy into the tmux buffer using the standard [ , space , move to select , enter or you can select a block of code. Also this is particularly useful when you are inside one of the lanes of the cli multiplexer like tmux AND you need to select a bunch of text, but not the line numbers (my vim setup renders line numbers)

在此之后,您可以使用命令:

tmux save-buffer - | xclip -i

当然,您可以将其命名为您喜欢的名称,或者直接绑定到tmux配置文件中

这只是给您一个概念性的答案,以覆盖这种不可能再次执行命令的边缘情况。如果您需要更具体的代码示例,请告诉我

干杯

对于mac,这是一个示例方法复制(到剪贴板)粘贴(从剪贴板)使用命令行

将pwd命令的结果复制到剪贴板as

$ pwd | pbcopy

使用剪贴板中的内容通过您的机器的快捷方式进行粘贴或在命令中,如下所示

$ cd $(pbpaste)

我在这里创建了一个工具

取决于xclip包

使用.bashrc脚本的本机解决方案

Linux, macOS, Windows (WSL/CYGWIN)

这些系统都使用自己的工具将剪贴板功能合并到命令行界面(CLI)中。这意味着,当使用例如在Windows子系统for Linux (WSL)上的Ubuntu命令行时,通常的xclip解决方案将不起作用。这同样适用于macOS。

下表概述了在不同系统上需要的复制/粘贴工具:

OS Copy Paste
WSL clip.exe powershell.exe Get-Clipboard
CYGWIN > /dev/clipboard cat /dev/clipboard
macOS pbcopy pbpaste
Linux xclip -sel clip xclip -sel clip -o

统一的。bashrc解决方案

只需将以下代码放入~/。允许在所有系统上使用复制和粘贴。该解决方案适用于“正常”Linux系统(即Ubuntu, Debian)以及WSL和macOS:

if grep -q -i microsoft /proc/version; then
  # on WSL: version contains the string "microsoft"
  alias copy="clip.exe"
  alias paste="powershell.exe Get-Clipboard"
elif grep -q -i cygwin $(uname -a); then
  # on CYGWIN: uname contains the string "cygwin"
  alias copy="/dev/clipboard"
  alias paste="cat /dev/clipboard"
elif [[ ! -r /proc/version ]]; then
  # on MAC: version is not readable at all
  alias copy="pbcopy"
  alias paste="pbpaste"
else
  # on "normal" linux
  alias copy="xclip -sel clip"
  alias paste="xclip -sel clip -o"
fi

在所有系统上使用

复制:

# pipe
echo "hello world" | copy

# or for direct file input
copy < file

粘贴:

paste > file

我使用Parcellite和xsel复制上次提交消息从git到我的剪贴板管理器(由于某种原因xclip不工作):

$ git log -1 --pretty=%B | xsel -i -b