Monday, 8 December 2014

Using RSYNC to copy only certain files matching a pattern/wildcards in a directory tree in bash/linux

create this file:
rsync-only-files-matching:
#!/bin/bash
if [ "$3" == "" ]
then
  echo "syntax:  $0 [pattern] [from_dir] [to_dir]"
  echo "example: $0 \"*.txt\" ./ 192.168.1.100:/home/user/target_dir/"
  exit 255
fi

rsync -vtrla --progress --partial --prune-empty-dirs --include='*/' --include="$1" --exclude='*' "$2" "$3"

now you can do:
./rsync-only-files-matching "*.txt" source/dir/ target/dir/
i
Note: 
  • because it's rsync, the trailing slash in the source dir tells it to copy the files (excluding hidden ones) in that directory. Omitting it means you'll copy the directory itself
  • You can omit the double quotes on the pattern if there are no files matching it in the current directory. It's just to prevent the shell from expanding it as a local path.