Moving specific files to specific folders

I can create new subfolders based on the first 3 letters of specific filenames with the script below.
cd '/Users/e_isbell/Documents/4y_GNG';
files = dir('*.set');
for i=1:length(files)
filename = files(i).name;
folder = filename(1:3);
mkdir('/Users/e_isbell/Documents/4y_GNG',folder);
end
However, I can't figure out how to move several files that start with those first 3 letters to the matching subfolders.
For instance, I have several files that has '150' for the first 3 letters (the following letters are different for each file). I want to create a subfolder that has these first 3 letters in its name (e.g. '150'), which I can do with the script above. Then I want to move all the files that start with '150' into the subfolder named '150'; all files that start with '155' into the subfolder named '155' and so on, looping through the folder.

Réponses (2)

Thorsten
Thorsten le 15 Juil 2016
Modifié(e) : Thorsten le 15 Juil 2016
direc = dir; filenames = {};
[filenames{1:length(direc),1}] = deal(direc.name);
first3 = cellfun(@(x) x(1:3), filenames, 'Uni', 0);
mypath = '/Users/e_isbell/Documents/4y_GNG';
for f3 = unique(first3)
mydir = fullfile(mypath, f3);
mkdir(mydir)
movefile([f3 '*'], mydir)
end
elisbe
elisbe le 15 Juil 2016

0 votes

Thanks for the promptly reply. This is the error I get:
Error using cellfun Input #2 expected to be a cell array, was struct instead.

1 commentaire

Thorsten
Thorsten le 15 Juil 2016
Uups, I thought that 'files' are the filenames. I've updated my response.

Connectez-vous pour commenter.

Catégories

En savoir plus sur File Operations dans Centre d'aide et File Exchange

Question posée :

le 15 Juil 2016

Modifié(e) :

le 15 Juil 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by