MATLAB: Search for a file using edit text with a part of the file name

fileguimatlab guisearch filesuser interface

Hello everyone,
Does anybody know how to find a file in a folder with a certain part of the file name? So whether someone's leaves out the extension or a part of it, it will still find the correct file? Now I have this code that allows the user to find a file in 'folder name', but the user would have to enter the entire filename instead of part of it. I have seen things like dir(.) but I cannot seem to make it work
Thanks for the help!
% --- Executes on button press in findfile1.
function findfile1_Callback(hObject, eventdata, handles)
% hObject handle to findfile1 (see GCBO)
% eventdata reserved - to be defined in a future version of MATLAB
% handles structure with handles and user data (see GUIDATA)
foldername = handles.foldername;
files = dir(fullfile(foldername, '*.csv'));
files = {files.name}';
for k = 1: length(files);
fname = fullfile(foldername,files{k});
end
filename = get(handles.edit1, 'String');
filename = char(filename);
if 2 == exist(fullfile(foldername,filename), 'file')
%csvread(files);
Filename = sprintf('file exists:\n%s', filename);
uiwait (msgbox(Filename));
else
warningMessage = sprintf ('Warning: file does not exist:\n%s' , filename);
uiwait(msgbox(warningMessage));
end

Best Answer

You could experiment with dir:

str = '0283';
fmt = sprintf('*%s*.csv',str);
S = dir(fmt);
filename = S.name

Or perhaps:

fmt = sprint('ID%s15sec.csv',str);

One flexible solution would be to let the user define as much of the filename as they want, find all matches, and then filter for only those that match the required filename pattern:

str = '0283';
S = dir(sprintf('*%s*',str));
N = {S(~[S.isdir]).name};
idx = ~cellfun('isempty',regexp(N,'^ID\d{4}15sec\.csv$'));
filename = N{idx}

Note:

  • you will need to add the filepath.
  • you will need to add checks to see if zero/multiple files match what the user gives. If you omit this it will only cause problems later!

As an alternative, you could simply use uigetfile.