How to copy specific files while preserving the folder structure

Maith Egeek
1 min readOct 2, 2023

The answer in short is rsync. rsync is better suited for maintaining the directory structure during file transfers.

The command to copy recursively from subfolders files ending with ‘Anomymised.mp4’ to a remote server path, while preserving the subfolders structure, is :

rsync -av --include='*/' --include='*Anonymised.mp4' --exclude='*' /path/to/local/directory/ username@remote_server:/path/to/remote/directory/

Let’s break down the command:

  • rsync: The command for synchronizing files and directories.
  • -av: Options for archive mode and verbose output. The archive mode -a ensures that permissions, timestamps, and other file properties are preserved.
  • --include='*/': This option includes directories in the sync process.
  • --include='*Anonymised.mp4': This includes files with the "Anonymised.mp4" pattern. Change this to select your files pattern.
  • --exclude='*': This excludes all other files.
  • /path/to/local/directory/: Replace this with the path to the local directory where your files are located.
  • username@remote_server:/path/to/remote/directory/: Replace this with your remote server's username, server address, and the path to the remote directory where you want to copy the files.

This rsync command will copy all files matching the pattern while preserving the folder structure to the remote server.

--

--