How to copy files by extension recursively

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
  • "-p" option enables a recursive copy operation.
  • "-d" option creates leading directories where needed.
  • "-m" option retains previous file modification times while files are copied to the destination location.

Subscribe to Xmodulo

Do you want to receive Linux FAQs, detailed tutorials and tips published at Xmodulo? Enter your email address below, and we will deliver our Linux posts straight to your email box, for free. Delivery powered by Google Feedburner.

Support Xmodulo

Did you find this tutorial helpful? Then please be generous and support Xmodulo!

The following two tabs change content below.
Dan Nanni is the founder and also a regular contributor of He is a Linux/FOSS enthusiast who loves to get his hands dirty with his Linux box. He likes to procrastinate when he is supposed to be busy and productive. When he is otherwise free, he likes to watch movies and shop for the coolest gadgets.

Leave a comment

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