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
?
Best Answer
As the
cp
error indicates, the target directory must come last. Since it looks like yourcp
doesn't have an equivalent of GNUcp
's-t
option, you have to get xargs to insert the filename betweencp
and.
: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: