Can I exclude files during recursive copy?

QuestionsQuestions8 SkillsProBasic Files OperationsOct, 28 2025
0130

Yes, you can exclude files during a recursive copy using the rsync command, which provides more flexibility than the cp command. The rsync command allows you to specify patterns for files you want to exclude.

Example

Here's how to use rsync to copy a directory while excluding certain files:

rsync -av --exclude='*.txt' /source_directory/ /destination_directory/

In this example:

  • -a stands for "archive" mode, which preserves permissions and timestamps.
  • -v stands for "verbose," which provides detailed output.
  • --exclude='*.txt' tells rsync to exclude all files with the .txt extension.

Using cp with find

If you prefer to use cp, you can combine it with the find command to exclude certain files, but it's a bit more complex. Here's an example:

find /source_directory -name '*.txt' -prune -o -exec cp -r {} /destination_directory/ \;

In this command:

  • -name '*.txt' -prune excludes files matching the pattern.
  • -o means "or," allowing the command to continue with the next part.
  • -exec cp -r {} /destination_directory/ \; copies the remaining files.

Using rsync is generally the simpler and more efficient method for excluding files during a recursive copy.

0 Comments

no data
Be the first to share your comment!