If you want to copy all the .txt
files in a directory, use a wildcard pattern:
cp direct/direct1/*.txt target
This copies all the .txt
files that are in the directory direct/direct1
to the directory target
(which must already exist).
You can pass multiple patterns to copy files from multiple directories:
cp direct/direct1/*.txt direct/direct2/*.txt target
If you want to copy the .txt
files from all the subdirectories of direct
, you can use a wildcard for the directory as well:
cp direct/*/*.txt target
If you only want to copy from certain directories, you can use a wildcard pattern that matches only these directories. For example, if direct
has four subdirectories foo
, bar
, baz
and qux
and you only want to copy files from bar
and baz
, you can use
cp direct/ba?/*.txt target
None of the examples so far copy files from direct
itself, or from subsubdirectories of direct
. If you want to copy the .txt
files from direct
, you need to include it in the list, e.g.
cp direct/*.txt direct/*/*.txt target
If you want to copy files from direct
, all of its subdirectories, all of their subdirectories, and so on recursively, you can use the **
wildcard, if your shell supports it. It works out of the box in zsh, but in bash, you need to enable it first with shopt -s globstar
.
cp direct/**/*.txt target
Note that all the files are copied into target
itself, this does not reproduce the directory structure. If you want to reproduce the directory structure, you need a different tool, such as rsync (tutorial) or pax.
rsync -am --include='*.txt' --include='*/' --exclude='*' direct/ target/
cd direct && pax -rw -pe -s'/\.txt$/&/' -s'/.*//' . target/
cp direct/direct*/*.txt /destination
orprintf '%s\0' direct/direct*/*.txt | pax -rw0 /destination
? – Stéphane Chazelas May 22 '15 at 11:35find /path/to/direct -name "*.txt" -exec cp {} /destination
; – Lambert May 22 '15 at 11:47\;
but+
in that command – Anthon May 22 '15 at 11:58+
instead of\;
you are not able to specify a target directory. Thecp
command will not take multiple sources. Please correct me if I am wrong – Lambert May 22 '15 at 12:10mkdir tmp; cd tmp; touch a b c d; mkdir t; cp a b c d t; ls t;
showsa b c d
– Anthon May 22 '15 at 12:12+
before and it does not work in my case:mkdir s; find t/ -exec cp {} s +
gives me:find: missing argument to '-exec'
– Lambert May 22 '15 at 12:16find /path/to/direct -name "*.txt" | xargs | xargs -I{} cp {} /destination
works better than using the+
option. BTW, I found a confirmation to your correction in the manual of cp:Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.
I completely overlooked that. – Lambert May 22 '15 at 12:41