pass output as an argument for cp in bash [duplica

2019-02-01 19:25发布

This question already has an answer here:

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.

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

标签: linux bash unix ls cp
4条回答
\"骚年 ilove
2楼-- · 2019-02-01 19:34

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.

查看更多
我想做一个坏孩纸
3楼-- · 2019-02-01 19:35

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
查看更多
forever°为你锁心
4楼-- · 2019-02-01 19:41

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
查看更多
做自己的国王
5楼-- · 2019-02-01 19:56

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
查看更多
登录 后发表回答