Copy overlapping files based on extension from multiple directories

132 Views Asked by At

I have files in multiple directories which I want to copy only those whose extensions are found on all of the directories. Here is an example:

dir1
    file1.txt  
    file2.bcd
    file3.aa

dir2
    file4.ogg
    file5.txt
    file6.bcd

dir3 
    file7.pgp
    file8.bcd
    file9.aa

The copy command or script shall copy only file2.bcd and file6.bcd and file8.bcd to the Output directory as they're the once common to all directories. This is just an example and the directories have file extensions which has nothing to do with the file type and I want to copy those common to all directories.

Output
   file2.bcd
   file6.bcd 
   file8.bcd  

Had I known the overlapping file extensions in advance, I could have used find, cp or mv as discussed here.

Thank you for your help,

Edit: I have solved the problem as follows in case anyone needs it.

1. Find and print only file extensions. 
2. Sort and count the extensions. 
3. If count equals folders searched, then copy file to output directory. 

Of course, this approach assumes each file extension is found once and only once in each folder and which happens to be the case of my files.

1

There are 1 best solutions below

3
On

You can use find command to copy files to the output dir using find ./ -type f -name '*.<file_ext>' -exec cp -r {} /output/ \;

replace file_ext with file extension.