开发者

pass output as an argument for cp in bash [duplicate]

This question already has answers here: How to pass command output as multiple arguments to another command (5 answers) Closed 6 years ago.

I'm tak开发者_StackOverflow中文版ing 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.

I can get the 5 largest files but I don't know how to pass them into cp in one command

ls -SF | grep -v / | head -5 | cp ? Directory


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.


I would do:

cp $(ls -SF | grep -v / | head -5) Directory

xargs would probably be the best answer though.

ls -SF | grep -v / | head -5 | xargs -I{} cp "{}" Directory


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."

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:

ls | while read varname; do echo $varname; done


If your cp has a "-t" flag (check the man page), that simplifies matters a bit:

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 . -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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜