cp Command – cp Recursive with Specific File Extension

bashcommand linecp

I am trying to copy all .odt files including those in subdirectories.

cp -r ~/Documents/* ~/copies # works as expected
cp -r ~/Documents/*.odt ~/copies # does not work as expected

The first line will copy all files and in all subdirectories but the second will copy only the .odt files in ~/Documents and none of the files in the subdirectories.

Best Answer

If you wish to replicate the directory structure (more like what cp -r does as suggested by steeldriver) but only populate it with the .odt files, you can do it with rsync, where -f is the 'filter' option. The other options are more straight-forward. You find all the options in man rsync.

rsync -nvr -f '+ *.odt' -f '+ **/' -f '- *' --prune-empty-dirs ~/Documents/ ~/copies/

It is a good idea to use the 'dry run' option -n and the verbose option -v in order to see what will be done before running the real command (when n is removed from the command line).