How to select files that contain a particular string as part of their name?
71 次查看(过去 30 天)
显示 更早的评论
Hello,
I am new to MATLAB and coding in general. I figured out how to loop through files in a directory but I want to be able to edit them based on whether they contain one string or another as part of their file name (red, green, or blue). I have listed what I have so far below. The file names are long and generally look something like this "16011201-04_10x_section-8_EGFP-CY3-Image Export-02_c1+2.tif (Red Results).xls" Any help would be appreciated.
SpreadSheetInput = uigetdir('','Select folder containing ImageJ macro data');
disp('You have selected')
disp(SpreadSheetInput)
files = dir(fullfile(SpreadSheetInput, '*.xls'));
files = rmfield(files, 'date');
files = rmfield(files, 'bytes');
files = rmfield(files, 'datenum');
files = rmfield(files, 'isdir');
for i = 1:length(files)
disp(files(i))
if
%Not sure what to put here.
end
end
0 个评论
回答(2 个)
KSSV
2016-7-20
You can use strcmp to compare to strings and strfind to find whether the user input string exists in the given string.
Ex;
filename = 'Red Results.xls'
if strfind(filename, 'Red')
% do waht you want
end
In the above ex. the filename has string Red...so it will go inside loop...be careful in specifying the word you want to find/ match.
0 个评论
Stephen23
2016-7-20
编辑:Stephen23
2016-7-20
The answer really depends on what you want to do: how do you plan on working with those filenames? Something like this might work for you:
D = uigetdir(pwd,'Select Directory');
S = dir(fullfile(D,'*.xls'));
%
for k = 1:numel(S)
N = S(k).name;
disp(N)
R = regexp(N,'(Red|Green|Blue)','match','once');
switch R
case 'Red'
disp Red
case 'Green'
disp Green
case 'Blue'
disp Blue
end
end
tested on these files:
2 个评论
Stephen23
2016-7-20
编辑:Stephen23
2016-7-20
@T Lavin: the error message clearly shows that the code you are running has nothing to do with the code that I gave in my answer.
I wrote code to read the filenames, and distinguishes them depending on the presence of Red/Green/Blue in the filename. It works without error: I tested it.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 String Parsing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!