16

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?

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

1 Answer 1

28

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 {} . \;
2
  • 5
    Tip: don't use -I _ if your command also contains underscores. It took me way too long to figure that one out.
    – compie
    Oct 17, 2019 at 9:20
  • The pure find command worked for me, thanks.
    – james-see
    Apr 4, 2022 at 23:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .