How to transfer only a certain file extension with rsync

Rsync is the tool of choice if you have to transfer files from a server to another one. The tool is very powerful and has a lot of options, but is not that easy to use when you have in mind what you need to do but you don’t know how.

One tricky situation is when you have to sync files with only a certain fileĀ  extension, for example if you want to transfer only .txt files or .pdf or .jpeg from your remote.

The solution for this task is to use something like this:

rsync -am --include='*.txt' --include='*/' --exclude='*' SOURCE/ DESTINATION/

Let’s see what does it mean.

Let’s start from the -a option. This is a very common option for rsync. It tells rsync to go in “archive” mode where user, permissions, time and so on are maintained on the destination. It’s what people usually want’s to happen, so here it is.

Then we jump a little ahead to the two –include and one –exclude. To transfer only one particular file extension we have first to exclude anything, that’s why we have the star exclude. Then we have to explicit include only *.txt, that’s pretty obvious. For last we have an include for anything that is a folder. This is needed because the exclude excludes really anything and so we have to re-include folders in this way.

If we stop here rsync will transfer all file with the correct extension and all folders, even empty folder. Not exactly what we want and so there comes the -m options, a shortcut for –prune-empty-dirs. This option will not transfer any empty folder keeping our destination folder as clean as possible.

That’s all!

2 thoughts on “How to transfer only a certain file extension with rsync

Leave a Reply

Your email address will not be published. Required fields are marked *