I have a directory which has many sub-folders and under sub-folders there are other sub-folders. I want to copy all the directory and subdirectories into another location with copying only files with certain names in these directories (while preserving the hierarchy).

Let's say, copy all the directory and sub-directories, then if these directories have files with .txt extensions, copy them too.

What is the best way to do this on a Unix/Linux system?

2 Answers 2


Using rsync:

rsync -a --include='*/' --include='*.txt' --exclude='*' source_dir/ target_dir

This should create a copy of the source_dir directory hierarchy as target_dir, with files whose names match *.txt copied (only).

The --include and --exclude options are handled in a left-to-right fashion and the first pattern that matches a name "wins". The way these options are used here ensures that all directories are processed, as well as any name matching *.txt, but ignores everything else.

The -a (--archive) option ensures that the source_dir hierarchy is processed recursively, and that as much as possible of file meta data is preserved in the copy (see the rsync manual for details).

  • Thank you! Works great!
    – Watzinki
    Nov 19, 2020 at 10:37

Ensure that the (absolute) destination directory exists:

mkdir -p "$DST_DIR"

Go to the source directory (it shouldn't be a descendant or parent of $DST_DIR):

cd "$SRC_DIST"

Re-create the directory structure (this will fail if you have directories with '\n' in their names):

find . -type d -print | xargs -I% mkdir -p "$DST_DIR"/%

Copy the interesting files there (in this example: *.txt and *.h):

find . \( -name \*.txt -o -name \*.h \) -print0 | cpio -pvdm0 "$DST_DIR"


If don't want directories that don't contain target files, you could just do:

find . \( -name \*.txt -o -name \*.h \) -print0 \
| cpio -pvdm0 $DST_DIR
  • Thanks for the answer. I noticed your answer after seeing the following solution and selecting it .
    – Watzinki
    Nov 19, 2020 at 10:40

You must log in to answer this question.

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