Bash 捕获命令的输出作为命令行未完成的输入

Bash capture output of command as unfinished input for command line

不知道这是否可行,但肯定会 convenient.I 想要获取 bash 命令的输出并以交互方式使用它来构建下一个Bash shell 中的命令。一个简单的例子如下:

> find . -name myfile.txt
/home/me/Documents/2015/myfile.txt

> cp /home/me/Documents/2015/myfile.txt /home/me/Documents/2015/myfile.txt.bak

现在,我可以做:

find . -name myfile.txt -exec cp {} {}.bak \;
or
cp `find . -name myfile.txt` `find . -name myfile.txt`.bak
or
f=`find . -name myfile.txt`; cp $f $f.bak

我知道。但有时你需要做一些比仅仅为文件名添加扩展名更复杂的事情,而不是参与 ${f%%txt}.text.bak 等等,它会更容易和更快(当你复杂性越来越大)只需将最后一个命令的结果弹出到交互式 shell 命令行并使用 emacs 样式的编辑键来执行您想要的操作。

那么,有没有什么方法可以将命令的结果通过管道传送回交互式 shell 并将其保留在那里。或者直接将其通过管道传输到 cut/paste 缓冲区并使用快速 ctrl-v 恢复它?

键入 M-C-e 扩展当前命令行,包括命令替换,就地:

$ $(echo bar)

现在输入 M-C-e 会将您的行更改为

$ bar

M-C-e 是 Readline 函数 shell-expand-line 的默认绑定。)


对于你的具体例子,你可以从

开始
$ cp $(find . -name myfile.txt)

shell-expand-line 扩展到

$ cp /home/me/Documents/2015/myfile.txt

然后您可以使用

进一步扩充
$ cp /home/me/Documents/2015/myfile.txt

从这里开始,您可以使用很多选项来完成命令行。两个比较简单的是

  1. 您可以使用历史扩展(!#:1.txt)来扩展到目标文件名。
  2. 您可以使用大括号扩展 (/home/me/Documents/2015/myfile.txt{,.bak})。

如果您在 Mac,您可以使用 pbcopy 将命令的输出放入剪贴板,以便您可以将其粘贴到下一个命令行:

find . -name myfile.txt | pbcopy

在 X 显示器上,您可以使用 xsel --input --clipboard(或 --primary,或者可能是其他选择名称,具体取决于您的 window 经理)执行相同的操作。您可能还有 xclip 可用,其工作方式类似。