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
qux and you only want to copy files from
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/