62

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
2

4 Answers 4

91

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.

2
  • 3
    While this may work, be aware Why you shouldn't parse the output of ls(1)
    – iolsmit
    Jul 24, 2018 at 11:37
  • You're right. It is however difficult to list the files in order by size, and ls -SF is easy enough. In fact, this solution is not correct if the files have spaces in them. Jul 25, 2018 at 8:20
61

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
1
  • 3
    Highly useful. Would be nice to explain the various options and their logic.
    – Hack-R
    Apr 25, 2019 at 17:57
9

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
1
  • That's exactly what I needed to pipe a list of window ids (grepped and cut from the output of xwininfo) into the xdotool so I could close a bunch of error dialogs that popped up. This syntax works with zsh :)
    – Desty
    Feb 10, 2016 at 13:14
2

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
2
  • I checked the man page on my system (macOS 10.12.1), and the -t option doesn't appear to exist: ~$ cp -t main.c main2.c cp: illegal option -- t
    – Vivek Gani
    Nov 7, 2016 at 0:24
  • 1
    I think the -t is a GNU option and Mac is not GNU. Nov 7, 2016 at 0:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.