Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
up vote 3 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

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