This is a bit of a basic question but I'm trying to copy all .doc files I find in a directory and copy them to another directory.

I know each command:

find -name '*.doc' .

and:

cp filename location 

How can I combine the two commands?

link|improve this question
feedback

3 Answers

up vote 2 down vote accepted
find /path/to/search -name "*.doc" -exec cp {} /path/to/copy/to \;

If there are a lot of .doc files this is your best option to avoid hitting the character limit.

link|improve this answer
Or equivalently, but slightly faster: find /path/to/search -name "*.doc" -exec cp -t /path/to/copy/to {} + – Gilles Nov 7 '10 at 23:29
@Gil, not equivalent, and not immune to the character limit. – John T Nov 7 '10 at 23:36
@John: How are they not equivalent? As for the character limit, find -exec … {} + is immune to it (it operates like xargs without the quoting issues). – Gilles Nov 7 '10 at 23:57
@gil take a closer look at the man pages, or, try it out with a few hundred thousand files in a deeply nested long path. – John T Nov 8 '10 at 0:19
@John: About the limit: citing POSIX: “The size of any set of two or more pathnames shall be limited such that execution of the utility does not cause the system's {ARG_MAX} limit to be exceeded.” Citing find(1) on Debian lenny: “The command line is built in much the same way that xargs builds its command lines.”. And I just tested on Debian lenny, it did break up the file names into chunks correctly. About the equivalence: again, what difference do you see? – Gilles Nov 8 '10 at 0:28
show 2 more comments
feedback

Another possibility:

find /path/to/search -name \*.doc -print0 | xargs -0 cp --target-directory=/destination/path

This cuts down on the number of invocations of the copy command when compared to find -exec (should be noticeably faster if you have a huge number of files)

link|improve this answer
feedback
cp *.doc /the/dir/you/want/to/copy/to
link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.