malmo
malmo

Reputation: 524

copy multiples files from multiples directories into one directory using MATLAB

How can I manage to copy the files from multiple directories into one target directory IN MATLAB for example if the directories are organized as follow:

directory1
 sub-directory1
   sub-sub-directory1-1
         file1
         file2
   sub-sub-directory1-2
         file4
         thisis-my-file
 sub-directory2
   sub-sub-directory2-1
          file
          myfile
 sub-sub-directory2-2
          file-case1

the result should be something like this:

target-directory
  file1
  file2   
  file4
  thisis-my-file
  file
  myfile
  file-case1

Upvotes: 0

Views: 344

Answers (2)

Krunal V
Krunal V

Reputation: 1253

you can use a matlab command for copying files which is copyfile('source','destination') like

 copyfile('directory1/sub-directory1/sub-sub-directory1-1/file1.txt','target-directory')
 copyfile('directory1/sub-directory1/sub-sub-directory1-1/file2.txt','target-directory')
 copyfile('directory1/sub-directory1/sub-sub-directory1-2/file4.txt','target-directory')
 copyfile('directory1/sub-directory1/sub-sub-directory1-2/thisis-my-file.txt','target-directory')
 copyfile('directory1/sub-directory2/sub-sub-directory2-1/file.txt','target-directory')

like this way for all of your file and you get those file in your destination folder. you can also give a complete path of the each source and destination also.

Upvotes: 0

bushmills
bushmills

Reputation: 673

here is one of many possible solutions:

First, get all subfolders of your directory1:

% define the destination folder
destinationFolder = 'c:\temp';
% genpath delivers all subfolders of the given directory
directories = genpath('C:\directory1'); 
% the following regular expression gets all these subfolder, seperated by ';'
directories = regexp([directories ';'],'(.*?);','tokens'); 

Now you can use the dir-function inside a for-loop for getting all the files in the subfolders:

for i=1:length(directories)
    % you could use a wildcard, if you only want some 
    % specific files to be moved in to the target directory.
    % (filesep is a built-in function!)
    files = dir([directories{i}{1} filesep '*.*']); 

    % use a second loop for copying your files
    for j=1:length(files)
        % build the path and copy the file to the desired destination
        copyfile([directories{i}{1} filesep files(j).name)], destinationFolder);
    end;
end;

Upvotes: 1

Related Questions