Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

This question already has an answer here:

I have a bunch of text files in several directories I want to copy into another. What can I do, instead of going inside each directory and cp *.txt in this directory?

share|improve this question

marked as duplicate by guntbert, Radu Rădeanu, Kevin Bowen, Eric Carvalho, mikewhatever Sep 8 '13 at 19:10

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
no because my files are located in multiple folders and I want to copy them to another –  bigTree Sep 7 '13 at 20:35
    
@bigTree Are the folders themselves in the same parent directory? –  minerz029 Sep 7 '13 at 20:54
    
I think this answer could be merged with the other question. –  Braiam Sep 7 '13 at 21:01
    
@minerz029 yes they are –  bigTree Sep 7 '13 at 21:10
add comment

1 Answer 1

up vote 2 down vote accepted

If none of the answers in the related threads is what you're looking for, you could consider using the find command, which will search directories recursively downwards from a given parent. You can specify an exec action to perform on each of the matching files that it finds - in this case, you'd want it to perform a cp to a new target directory

find /path/to/parent -name '*.txt' -exec cp -t /path/to/newdir {} +

The {} is replaced by the files that it locates, and the + at the end causes it to batch them so as not to overflow the maximum number of arguments that cp can handle in one command. The newdir must already exist.

Since you are moving files from many places to one place, there is a possibility that some names will be non-unique, and so you may want to take care to prevent an earlier copy from being overwritten by a later copy - you can do that by adding a backup option

find /path/to/parent -name '*.txt' -exec cp --backup=numbered -t /path/to/newdir {} +

which will add a simple numbered suffix to each duplicate file. You can add a -v or --verbose flag to the cp if you want to see a running report of the files as it copies them.

share|improve this answer
add comment

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