1

I'd like to copy the files searched by command find to the currernt directory

    # find linux books
    find ~ -type f -iregex '.*linux.*\.pdf' -print0 | xargs -0 echo
  # the result
    ../Books/LinuxCollection/Linux_TLCL-17.10.pdf ../Richard Blum, Christine Bresnahan - Linux Command Line and Shell Scripting Bible, 3rd Edition - 2015.pdf ..

Test to copy the files to the current dir using command `cp'

 find ~ -type f -iregex '.*linux.*\.pdf' -print0 | xargs -0 cp .

Get error:

    usage: cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file target_file
           cp [-R [-H | -L | -P]] [-fi | -n] [-apvXc] source_file ... target_directory

I work out the problem with command substitution

    cp $(find ~ -type f -iregex '.*linux.*\.pdf' -print0) .

How to accomplish it with xargs?

  • Why do you want to pipe the output of find into xargs? Wouldn't it be easier to use the find option -exec cp {} . \;? – user1934428 Mar 28 '18 at 6:36
3

As the cp error indicates, the target directory must come last. Since it looks like your cp doesn't have an equivalent of GNU cp's -t option, you have to get xargs to insert the filename between cp and .:

find ... | xargs -0 -I _ cp _ .

where -I is used to tell which string is to be replaced with the input (in this case I'm using _, though {} is also commonly used).

Of course, this can be done with find itself:

find ~ -type f -iregex '.*linux.*\.pdf' -exec cp {} . \;

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.