How to copy files by extension recursively

Last updated on October 17, 2020 by Dan Nanni

If you are wondering how to copy files of a specific extension (e.g., .txt, .php, .java) recursively, the following guide can help you. By copying files recursively, I mean that you copy files located in the current directory as well as its sub-directories, to another location which has the same directory structure.

Your first (unsuccessful) attempt may be using cp command with -r option.

$ cp -r *.txt /path/to/destdir

However, the above command will copy only *.txt files in the top-level current directory, but not in any of its sub-directories. So this is not the right way to do it.

A correct way to copy files recursively is to use cpio command, which is a Linux tool that copies files to and from archives. The command below demonstrates how to copy .txt files from one directory tree to another.

$ find /path/to/srcdir -name '*.txt' | cpio -pdm /path/to/destdir
The above command means the following:

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal or credit card

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean