How to Copy Files Recursively in Linux

Yahya Irmak Feb 02, 2024
How to Copy Files Recursively in Linux

Linux terminal is an easy and fast way to copy files and directories. Throughout this article, we will explain how to copy files in Linux with the cp command.

We will also use a wildcard * to copy files with similar names and recursively copy multiple files and directories.

The sample files and directories we will use throughout the article are below.

Files and directory structure

Use the cp Command to Copy Files in Linux

After the cp command, type the file sources you want to copy and the destination file or directory. The use of a slash / after the directory name is optional.

cp Folder/file1.txt Folder3/

Copy Files With the cp

Use Wildcard * to Copy Files With Similar Filenames in Linux

An asterisk * is called wildcard, and it gives every file that starts with the specified name as a parameter to the cp command.

We want to copy all files with the name file1, even if the extension is different. We use a wildcard instead of specifying the extension at the end of the filename.

cp Folder/file1.* Folder3/

Use Wildcard for Similar Filenames

Use Wildcard * to Copy Files With Same Extension in Linux

This time, we want to copy all files with the same extension, even if their names are different. We use a wildcard instead of the filename then write the extension.

cp Folder/*.txt Folder3/

Use Wildcard for Same Extension

Use the -r Flag to Copy Files Recursively in Linux

The -r or -R flag allows you to copy directories and their contents recursively. Type the directory name you want to copy after the cp -r command and the destination directory.

We can also use the -a flag. It is similar in functionality to the -r flag, but it copies the files without changing their metadata, such as creation date.

cp -r Folder/ Folder3/

Use the -r for copy recursively

Use the find Command to Copy Files Recursively in Linux

We can use the find command to recursively find and copy files with similar extensions or filenames from a directory and its sub-directories. The find command is used with the exec.

find Folder/ -name '*.txt' -exec cp -r {} Folder3 \;

Use find with exec

Author: Yahya Irmak
Yahya Irmak avatar Yahya Irmak avatar

Yahya Irmak has experience in full stack technologies such as Java, Spring Boot, JavaScript, CSS, HTML.

LinkedIn

Related Article - Linux File