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

ε祈祈猫儿з 提交于 2019-11-30 01:26:21

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
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!