Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rsync files with matching pattern in path by keeping directory structure intact?

Tags:

I want to copy all files from server A to server B that have the same parent directory-name in different levels of filesystem hierarchy, e.g:

/var/lib/data/sub1/sub2/commonname/filetobecopied.foo /var/lib/data/sub1/sub3/commonname/filetobecopied.foo /var/lib/data/sub2/sub4/commonname/anotherfiletobecopied.foo /var/lib/data/sub3/sub4/differentname/fileNOTtobecopied.foo 

I want to copy the first three files that all have the commonname in path to server B. I already spent a lot of time in finding the correct include/exclude patterns for rsync but I dont get it. The following command does not work:

rsync -a --include='**/commonname/*.foo' --exclude='*' [email protected]:/var/lib/data /var/lib/data 

I either match too much or to few of the files. How can I sync only the files with the commonname in its path?

like image 258
murks Avatar asked Feb 10 '15 18:02

murks


People also ask

Does rsync sync in both directions?

rsync works in one direction, so we need to run it twice to sync directories in both directions.

Does rsync skip identical files?

Files that have been updated will be synced, rsync will copy only the changed parts of files to the remote host. File that is exactly the same are not copied to the remote host at all.

How does rsync keep track of changes?

From man rsync : -c, --checksum This changes the way rsync checks if the files have been changed and are in need of a transfer. Without this option, rsync uses a "quick check" that (by default) checks if each file's size and time of last modification match between the sender and receiver.

What happens if files change during rsync?

rsync first scans the files and builds a list. so once the file is listed for sync, rsync will sync the latest change of file. but if the file is not in the list of files to be synced, which was built before starting the sync operation, then it will not sync it.


1 Answers

I guess you're looking for this:

rsync -a -m --include='**/commonname/*.foo' --include='*/' --exclude='*' [email protected]:/var/lib/data /var/lib/data 

There are 2 differences with your command:

  • The most important one is --include='*/'. Without this, as you specified --exclude='*', rsync will never enter the subdirectories, since everything is excluded. With --include='*/', the subdirectories are not excluded anymore, so rsync can happily recurse.
  • The least important one is -m: this prunes the empty directories. Without this, you'd also get the (empty) subdirectory /var/lib/data/sub3/sub4/differentname/ copied.
like image 72
gniourf_gniourf Avatar answered Sep 19 '22 20:09

gniourf_gniourf