2

I have more than 90 subdirectories and inside each one, there will be a number of .txt files.

What I need to do is to copy all those txt files out to one single directory.

How can I do that?

2
  • Are you seeking a minimal solution, or just something simple enough? Commented Aug 23, 2014 at 15:38
  • @richard the correct answer has given me what i need Commented Aug 23, 2014 at 15:53

2 Answers 2

5

use command :

find . -name "*.txt" -exec cp {} /path/to/destination \;
3
  • 1
    +1 Be careful though because if two files have the same basename one will be overwritten. Also you can make it a bit faster by replacing ... \; with ... +, since cp accepts more than two arguments.
    – user000001
    Commented Aug 23, 2014 at 16:01
  • 3
    @user000001 …-exec cp {} foo + gives an error, it appears that the {} has to be at the end of the command. Do you need to do …-exec cp -t foo {} + Commented Aug 23, 2014 at 16:23
  • 2
    @richard You are right it gives an error. Note to self: Never comment before testing :)
    – user000001
    Commented Aug 23, 2014 at 16:59
4

To avoid running one cp per file (as with -exec cp {} /dest \;):

find . -name '*.txt" -type f -exec sh -c '
  exec cp "$@" /path/to/destination' sh {} +

Or with GNU cp:

find . -name '*.txt" -type f -exec cp -t /path/to/destination {} +

With zsh:

cp ./**/*.txt(.) /path/to/destination

Or

cp ./**/*.txt(D.) /path/to/destination

If you want to include hidden files (or files in hidden dirs) like in the find solutions.

You must log in to answer this question.

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