2

I know how to use the cp command to recursively (-r) copy nested folders while preserving (-p) file meta-data such as modification times:

cp -pr "/path/from" "path/to"

Is there a way to omit one particular folder nested at the first level deep, by name?

For example, a folder named Photos is being copied. I want to skip the Dogs folder nested within. I want everything but not /Photos/Dogs folder nor its contents.

I suppose I could let it copy, then delete. But that is inefficient. Is there a way no avoid the folder copy in the first place.

I am working on macOS Mojave currently, and FreeBSD 12 later.

1 Answer 1

2

Yes, you can fairly easily make a copy of a file structure while avoiding copying one or several of the subdirectories, but you would not do it with cp.

With rsync, you can exclude files and/or directories using an exclusion pattern. In your case, it looks like you'd want to use

rsync -av --exclude='Photos/Dogs/' /path/from/ path/to

This would make path/to an exact copy of /path/from while avoiding any directory called Dogs at any path matching Photos/Dogs. If you remove the trailing / on the source directory, you'll instead get path/to/from as an exact copy of the source folder.

The exclude pattern used would make rsync ignore any subdirectory called Dogs located in a directory called Photos, for example /path/from/Photos/Dogs and /path/from/holidays/2013/Photos/Dogs. Using --exclude=Dogs/ would exclude any subdirectory called Dogs regardless of what its parent directory is called, and using --exclude=Dogs would exclude anything (regardless of file type) that is called Dogs. To match only a Photos/Dogs directory directly under /path/from, use --exclude='/Photos/Dogs/'.

See the section called "INCLUDE/EXCLUDE PATTERN RULES" in the rsync manual on your system.

The -a (--archive) option will make sure timestamps, permissions etc. are also copied, and also enable recursive copying. The -v (--verbose) option enables verbose operation.

Add -H (--hard-links) if you want to preserve hard linking between names (again, see the rsync manual).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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