stringcmp filenames with similar naming
2 次查看(过去 30 天)
显示 更早的评论
Hello:
Is there a good way to match files from different folders together?
I am considering using stringcmp, to load two different files together, but I am not sure how to approach this. Would you first use a for loop for recursion to search all folders and files one string character at a time? If so, what would be the matlab syntax?
2 个评论
回答(1 个)
Voss
2022-7-26
编辑:Voss
2022-7-26
"Is there a good way to match files from different folders together?"
Here's an approach using dir, fullfile, fileparts, strcat, and intersect that does what it seems like you are asking for:
% create some txt files in two directories:
rng(1000); % (for reproducibility of the random file names)
dirs = {'folder_1','folder_2/subfolder'};
for ii = 1:numel(dirs)
mkdir(dirs{ii});
for jj = randi(10,1,7)
fclose(fopen(fullfile(dirs{ii},sprintf('file_%03d.txt',jj)),'w'));
end
end
% get info about txt files in those two directories:
files_1 = dir(fullfile(dirs{1},'*.txt'));
names_1 = fullfile(dirs{1},{files_1.name}.')
files_2 = dir(fullfile(dirs{2},'*.txt'));
names_2 = fullfile(dirs{2},{files_2.name}.')
% use fileparts to get just the names (with extensions):
[~,fn_1,ext_1] = fileparts(names_1);
fn_1 = strcat(fn_1,ext_1)
[~,fn_2,ext_2] = fileparts(names_2);
fn_2 = strcat(fn_2,ext_2)
% use intersect to find which file names are in both directories:
intersect(fn_1,fn_2)
If this is not what you want to do, clarify what you want to do.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 File Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!