I coded like below:

$ find . -maxdepth 1 -name '*.jpg' | head -n 100 | xargs -0 {} cp {} /home/rachael/backup

Error showed:

xargs: {}: No such file or directory

What's wrong with my code and how can it fixed?


steeldriver pinpoints some of the issues with your command, but I just wanted to add a shorter solution using the zsh shell (as the question was not specific to any one shell):

cp -- *.jpg(.[1,100]) ~rachel/backup

This would copy the 100 first (by lexicographic ordering) regular files in the current directory that matches the globbing pattern *.jpg.

For the 100 oldest files by modification timestamp, use *.jpg(.Om[1,100]), and use a lower-case o instead of O to get the 100 most recently modified files. Use n in place of Om to get numeric sorting of the filenames, and add D to also match hidden names.

  • Which also has the benefit of copying the file in a consistent order (see also the the n glob qualifier to use a numeric order as jpg files tend to have numbers in them). See also the D glob qualifier to also consider hidden jpg files or jpg files in hidden directories (like find does by default). Sep 16 '19 at 11:51

A couple of things:

  1. You're missing a -I in your xargs command to tell it what the {} is to be used for

  2. The -0 tells xargs to expect null-delimited input, but you're passing it newline-delimited input


find . -maxdepth 1 -name '*.jpg' -print0 | head -zn 100 | xargs -0 -I{} cp {} /home/rachael/backup

If you have the GNU version of cp, you might want to use the alternate form

find . -maxdepth 1 -name '*.jpg' -print0 | head -zn 100 | xargs -0 cp -t /home/rachael/backup
  • 1
    +1. depending on what OP meant by "first" 100 files, it may also be worthwhile inserting a | sort -V -z before the | head -zn 100.
    – cas
    Sep 16 '19 at 6:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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