find and copy files in linux

How to Find & Copy Files in Linux

Sometimes you may need to find & copy files in Linux. Typically, people do this using two commands where they find the files first and then separately copy them. But you can easily do this together using a single find command. In this article, we will learn how to find & copy files in Linux.

How to Find & Copy Files in Linux

Let us say you want to copy all .pdf files in /home/data to /home/ubuntu folder. Here is the simple find command for this purpose.

find /home/data/ -name '*.pdf' -exec cp "{}" /home/ubuntu  \;

In the above command the find command, we specify search location as /home/data, filename to be searched as *.pdf, meaning all pdf files. We specify cp command using -exec option which allows us to execute commands on find command’s results. We call cp command and specify destination as /home/ubuntu.

Here is the general syntax to find and copy files using exec option.

find <path> <condition> -exec cp '{}' <copy path> \;

Alternatively, you can also use find and xargs command to find & copy files. Here is the command to do the above task using find and xargs.

find /home/data/ -name '*.pdf' | xargs cp -t /home/ubuntu

In the above command, the result of find command is passed to xargs command which constructs separate cp commands for each filename returned in find command. Here is the general syntax for finding and copying files using find and xargs command.

find <Path> <Conditions> | xargs cp -t <copy file path>

In this article, we have learnt how to find & copy files in Linux.

Also read:

How to Rename Downloaded File in Wget
Wget Limit Download Speed Rate
How to Backup & Restore PostgreSQL Database
How to Check Git Diff Between Commits
How to Checkout Specific Commit in Git

Leave a Reply

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