How can I sort files into different folders?

2 次查看(过去 30 天)
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

采纳的回答

Matthew Eicholtz
Matthew Eicholtz 2017-5-5
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 个评论
Matthew Eicholtz
Matthew Eicholtz 2017-5-5
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.
sal135
sal135 2017-5-5
Thank you! this worked. Just needed to add a loop to run through all files

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 String Parsing 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by