$ rsync --recursive --include="data.zip" --include="*.txt" --filter="-! */" dir_1 copy_of_dir_1
To exclude dir3
regardless of where it is in the tree (even if it contains files that would match the --include
s):
--exclude 'dir3/' (before `--filter`)
To exclude dir3
only at at specific location in the tree, specify an absolute path, starting from your source dir:
--exclude '/dir1/dir2/dir3/' (before `--filter`)
To exclude dir3
only when it's in dir2
, but regardless of where dir2
is:
--exclude 'dir2/dir3/' (before `--filter`)
Wildcards can also be used in the path elements where *
means a directory with any name and **
means multiple nested directories.
To specify only files and dirs to include, run two rsync
s, one for the files and one for the dirs. The problem with getting it done in a single rsync
is that when you don't include a dir, rsync
won't enter the dir and so won't discover any files in that branch that may be matching your include filter. So, you start by copying the files you want while not creating any dirs that would be empty. Then copy any dirs that you want.
$ rsync --recursive --prune-empty-dirs --include="*.txt" --filter="-! */" dir_1 copy_of_dir_1
$ rsync --recursive --include '/dir1/dir2/' --include '/dir3/dir4/' --filter="-! */" dir_1 copy_of_dir_1
You can combine these if you don't mind that your specified dirs don't get copied if they're empty:
$ rsync --recursive --prune-empty-dirs --include="*.txt" --include '/dir1/dir2/' --include '/dir3/dir4/' --filter="-! */" dir_1 copy_of_dir_1
The --filter="-! */"
is necessary because rsync includes all files and folders that match none of the filters (imagine it as an invisible --include
filter at the end of the list of filters). rsync
checks each item to be copied against the list of filters and includes or excludes the item depending on the first match it finds. If there's no match, it hits that invisible --include
and goes on to include the item. We wanted to change this default to --exclude
, so we added an exclude filter (the -
in -! */
), then we negate the match (!
) and match all dirs (*/
). Since this is a negated match, the result is that we allow rsync
to enter all the directories (which, as I mentioned earlier, allows rsync
to find the files we want).
We use --filter
instead of --exclude
for the final filter because --exclude
does not allow specifying negated matches with the !
operator.