Linux 在 bash 中将输出作为 cp 的参数传递
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6833582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
pass output as an argument for cp in bash
提问by Yamiko
I'm taking a unix/linux class and we have yet to learn variables or functions. We just learned some basic utilities like the flag and pipeline, output and append to file. On the lab assignment he wants us to find the largest files and copy them to a directory.
我正在学习 unix/linux 课程,但我们还没有学习变量或函数。我们刚刚学习了一些基本的实用程序,例如标志和管道、输出和附加到文件。在实验室作业中,他希望我们找到最大的文件并将它们复制到一个目录中。
I can get the 5 largest files but I don't know how to pass them into cp in one command
我可以获得 5 个最大的文件,但我不知道如何在一个命令中将它们传递给 cp
ls -SF | grep -v / | head -5 | cp ? Directory
采纳答案by Diego Sevilla
It would be:
这将是:
cp `ls -SF | grep -v / | head -5` Directory
assuming that the pipeline is correct. The backticks substitute in the line the output of the commands inside it.
假设管道是正确的。反引号在行中替换其中的命令的输出。
You can also make your tests:
您还可以进行测试:
cp `echo a b c` Directory
will copy all a
, b
, and c
into Directory
.
将全部复制a
,b
和c
成Directory
。
回答by gpojd
I would do:
我会做:
cp $(ls -SF | grep -v / | head -5) Directory
xargs would probably be the best answer though.
不过,xargs 可能是最好的答案。
ls -SF | grep -v / | head -5 | xargs -I{} cp "{}" Directory
回答by Brian Gordon
Use backticks `like this` or the dollar sign $(like this) to perform command substitution. Basically this pastes each line of standard ouput of the backticked command into the surrounding command and runs it. Find out more in the bash manpage under "Command Substitution."
使用反引号 `like this` 或美元符号 $(like this) 来执行命令替换。基本上,这会将反引号命令的每一行标准输出粘贴到周围的命令中并运行它。在“命令替换”下的 bash 联机帮助页中了解更多信息。
Also, if you want to read one line at a time you can read individual lines out of a pipe stream using "while read" syntax:
此外,如果您想一次读取一行,您可以使用“while read”语法从管道流中读取单行:
ls | while read varname; do echo $varname; done
回答by glenn Hymanman
If your cp
has a "-t" flag (check the man page), that simplifies matters a bit:
如果你cp
有一个“-t”标志(检查手册页),这稍微简化了一点:
ls -SF | grep -v / | head -5 | xargs cp -t DIRECTORY
The find command gives you more fine-grained ability to get what you want, instead of ls | grep
that you have. I'd code your question like this:
find 命令为您提供了更细粒度的能力来获得您想要的东西,而不是ls | grep
您拥有的东西。我会像这样编码你的问题:
find . -maxdepth 1 -type f -printf "%p\t%s\n" |
sort -t $'\t' -k2 -nr |
head -n 5 |
cut -f 1 |
xargs echo cp -t DIRECTORY