How can I sort files into different folders?
1 Ansicht (letzte 30 Tage)
Ältere Kommentare anzeigen
sal135
am 5 Mai 2017
Kommentiert: sal135
am 5 Mai 2017
I have a folder with n amount of files. Each file is saved as follows:
1n1 - type 3.csv
2n2 - type 3.csv
77fn.csv
3n3 - type 4.csv
4n4 - type 3.csv
5n5 - type 4.csv
6n6 - type 4.csv
7n7.csv
And so on. The files end with "type 3" or "type 4" or with a random name. I need the script to save all the files that end in "type 3" in a folder named "X" and the files that end with "type 4" to be stored in a folder named "Y". And the files that don't end neither with "type 3" nor "type 4" to be stores in a folder name Z. Any information is helpful. Thank you!
ALLfiles='\All_Files\';
X='\X\;
Y='\Y\';
Z='\Z\'
folder= ALLfiles;
data3=fullfile(folder,'*.csv');
directory=dir(data3);
for w=1:length(directory)
name{w}=getfield(directory(w),'name');
name{w}= strfind(name{w},'type 3');
%insert if statement, if "type 3" exists in name of the file, movefile to X
elseif "type 4" exist in name of the file movefile to Y
else move file to Z
end
0 Kommentare
Akzeptierte Antwort
Matthew Eicholtz
am 5 Mai 2017
Try this...
Get the filenames:
pathname = '\path\to\current\files';
ext = '*.csv'; % extension you care about
d = dir(fullfile(pathname,ext)); % get the relevant directory contents
filenames = {d(:).name}'; % relevant filenames
Create masks for the groups of files you are interested in using regexp:
mask1 = ~cellfun('isempty',regexp(filenames,'type 3'));
mask2 = ~cellfun('isempty',regexp(filenames,'type 4'));
mask3 = ~mask1 & ~mask2;
Copy (or move) the files from their source location to a new destination using copyfile (or movefile):
src = fullfile(pathname,filenames(mask1));
dest = fullfile('X',filenames(mask1));
cellfun(@copyfile,src,dest);
src = fullfile(pathname,filenames(mask2));
dest = fullfile('Y',filenames(mask2));
cellfun(@copyfile,src,dest);
src = fullfile(pathname,filenames(mask3));
dest = fullfile('Z',filenames(mask3));
cellfun(@copyfile,src,dest);
2 Kommentare
Matthew Eicholtz
am 5 Mai 2017
Hmm, can you tell me what pathname and filenames(mask1) look like for you? Pathname should be a string and filenames(mask1) should be a cell array of strings.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu String Parsing finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!