Is it possible to pipe the results of FIND to a COPY command CP?

Paul picture Paul · Oct 7, 2014 · Viewed 24.7k times · Source

Is it possible to pipe the results of find to a COPY command cp?

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:

  1. Why cant you just use | pipe? isn't that what its for?
  2. Why does everyone recommend the -exec
  3. How do I know when to use that (exec) over pipe |?

Answer

Good question!

  1. 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/
  1. 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.

  1. 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 ...)