Wednesday, March 1, 2017

[Quick Tips: Find File type & Backup]: How To Find and Copy Certain Type Of Files From One Directory To Another In Linux

How To Find and Copy Certain Type Of Files From One Directory To Another In Linux


There might be many ways to do this, but I found that the following method is really simple and handy. We will use ‘find’ command to achieve this goal. Find command comes pre-installed on most Unix-like distributions. So don’t bother installing it.  For the purpose of this guide, I will show how to quickly find and copy mp3 files from one directory called test1, to another directory called test2.

Let us check the contents of test directory.
ls /home/sk/test1
Sample output:
'Bombay Rockers - Sexy Mama.mp3' 'Marconi Union - Sleepless.mp3' wiua9.jpg
 books.txt Maruvaarthai.mp3
As you see in the above result, there three mp3 files in the test1 directory. I wanted to copy the mp3 files to another directory test2. Here is how to do this.
Go to test1 directory:
cd /home/sk/test1/
Then, run the following command to find and copy all files that ends with extension .mp3.
find -iname '*.mp3' -exec cp {} /home/sk/test2/ \;
Let us break down the above command and see what each option does.
  • find – It’s the command to fild files and folders in Unix-like systems
  • -iname ‘*.mp3’ – Search for files matching with extension .mp3
  • -exec cp – Tells you to execute the ‘cp’ command
  • {} – is automatically replaced with the file name of the files found by ‘find’ command
  • /home/sk/test2/ – Target directory to save the matching files
  • \; – Indicates it that the commands to be executed are now complete, and to carry out the command again on the next match.
That’s all. Now, let us go and check the test2 to verify if the files are copied correctly.
ls /home/sk/test2
Sample output would be:
'Bombay Rockers - Sexy Mama.mp3' Maruvaarthai.mp3
'Marconi Union - Sleepless.mp3'
As you can see the the files with extension .mp3 have been successfully copied from test1 directory to test2 directory. Similarly, you can copy all types of files without much effort to different directories. It will save you a lot of time. This trick could be helpful if you have large amount of different types of files in a directory.

No comments: