How to copy limited files from a directory tree to a target while maintaining the directory structure of the source
rsync is designed to make duplicates of a tree structure. While normally used to replicate a tree across the network, it is a fast, efficient tool to make local copies of of files also.
Using the filtering rules available, rsync can limit the files copied while maintaining the full directory structure. The syntax is:
rsync -av --prune-empty-dirs --exclude-from=exclude_file source dest
where exclude_file, source, and dest are, respectively, a file containing filtering rules, the source directory, and the target directory.
-av means run in archive mode and give verbose output
--prune-empty-dirs says to not copy any empty directories (otherwise the tree structure is copied)
exclude_file is the important part of this. It is a series of rules, one per line, which are processed in file order. The first item in a rule is a plus sign or a minus sign signifying include or exclude. This is followed by a space, then the matching text (see man rsync for more information). Comments can have a pound sign (#) in the first column, in which case the entire line is ignored. I have done this in the following to document what the following line does, though normally I don't bother for one-offs.
Sample exclude_file to copy all menu items and desktop links from a Windows Documents and Settings tree
# include all subdirectories, one level down
+ */ # include include all files and folders (full tree) below directory Start Menu
+ /*/Start Menu/** # include anything in directory Desktop that has a .lnk extension, from full tree
+ /*/Desktop/**.lnk # do not include anything else
The above is a real world example where the menus and desktop links were lost for all users on a Windows 2003 terminal server due to a virus. There was a full backup of c:\Documents and Settings on a unix machine and I recovered them with the following commands:
cd ~ mkdir recovered
# create the a file getMenus in the current directory containing the above rsync --prune-empty-dirs -av --exclude-from=./getMenus /home/backups/backup/server/ recovered
zip -r menu.zip recovered/
This created a zip file (transferable to the Windows machine) which could be unpacked over c:\Documents and Settings to recover the missing links.