-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindFilesWithStrings.m
More file actions
53 lines (44 loc) · 1.71 KB
/
findFilesWithStrings.m
File metadata and controls
53 lines (44 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
function matchingFiles = findFilesWithStrings(folderPath, searchStrings, extension, exactMatchStrings)
%FINDFILESWITHSTRINGS Finds files whose names contain all specified strings (case-insensitive),
% with optional exact token matching (e.g., 'WhiteNoise' not matching 'FrozenWhiteNoise').
%
% Inputs:
% folderPath - Folder to search in
% searchStrings - Substrings to match (case-insensitive)
% extension - (Optional) File extension filter (e.g., '.csv')
% exactMatchStrings - (Optional) Strings to match exactly as tokens
%
% Output:
% matchingFiles - Struct array of matching files (like dir)
if nargin < 3 || isempty(extension)
filePattern = fullfile(folderPath, '*');
else
if ~startsWith(extension, '.')
extension = ['.', extension];
end
filePattern = fullfile(folderPath, ['*', extension]);
end
if nargin < 4
exactMatchStrings = {};
end
allFiles = dir(filePattern);
matchingFiles = [];
for k = 1:length(allFiles)
file = allFiles(k);
if file.isdir
continue;
end
% Separate base filename (no extension)
[~, baseName, ~] = fileparts(file.name);
baseNameLower = lower(baseName);
% Case-insensitive substring match
hasSubstrings = all(cellfun(@(s) contains(baseNameLower, lower(s)), searchStrings));
% Tokenize base name using common separators
tokens = regexp(baseNameLower, '[^_\-\.]+', 'match');
% Case-insensitive exact match of tokens
hasExact = all(ismember(lower(exactMatchStrings), tokens));
if hasSubstrings && hasExact
matchingFiles = [matchingFiles; file];
end
end
end