Is it possible to pipe the results of FIND to a COPY command CP?
Solution 1
Good question!
- why cant you just use | pipe? isn't that what its for?
You can pipe, of course, xargs
is done for these cases:
find . -iname "*.SomeExt" | xargs cp Destination_Directory/
- Why does everyone recommend the -exec
The -exec
is good because it provides more control of exactly what you are executing. Whenever you pipe there may be problems with corner cases: file names containing spaces or new lines, etc.
- how do I know when to use that (exec) over pipe | ?
It is really up to you and there can be many cases. I would use -exec
whenever the action to perform is simple. I am not a very good friend of xargs
, I tend to prefer an approach in which the find
output is provided to a while
loop, such as:
while IFS= read -r result
do
# do things with "$result"
done < <(find ...)
Solution 2
There's a little-used option for cp
: -t destination
-- see the man page:
find . -iname "*.SomeExt" | xargs cp -t Directory
Solution 3
You can use |
like below:
find . -iname "*.SomeExt" | while read line
do
cp $line DestDir/
done
Answering your questions:
|
can be used to solve this issue. But as seen above, it involves a lot of code. Moreover,|
will create two process - one forfind
and another forcp
.Instead using
exec()
insidefind
will solve the problem in a single process.
Solution 4
Try this:
find . -iname "*.SomeExt" -print0 | xargs -0 cp -t Directory
# ........................^^^^^^^..........^^
In case there is whitespace in filenames.
Solution 5
This SOLVED my problem.
find . -type f | grep '\.pdf' | while read line
do
cp $line REPLACE_WITH_TARGET_DIRECTORY
done
Paul
BY DAY: Alt-Rock Ninja Cowgirl at Veridian Dynamics. BY NIGHT: I write code and code rights for penalcoders.org, an awesome non-profit that will totally take your money at that link. My kids are cuter than yours. FOR FUN: C+ Jokes, Segway Roller Derby, NYT Sat. Crosswords (in Sharpie!), Ostrich Grooming. "If you see scary things, look for the helpers-you'll always see people helping."-Fred Rogers
Updated on July 19, 2022Comments
-
Paul almost 2 years
Is it possible to pipe the results of
find
to a COPY commandcp
?Like this:
find . -iname "*.SomeExt" | cp Destination Directory
Seeking, I always find this kind of formula such as from this post:
find . -name "*.pdf" -type f -exec cp {} ./pdfsfolder \;
This raises some questions:
- Why cant you just use
|
pipe? isn't that what its for? - Why does everyone recommend the
-exec
- How do I know when to use that (exec) over pipe
|
?
- Why cant you just use