MATLAB: Read Only files (from a directory) that contain a specific string in filename

read specific files

I have a directory which contains a number of folders, each folder have data from different thermal bands. I need to read only files (from every folder in the directory) that contains B10 in the filename. Any suggestions ? On the left is the list of Folders in my directory and on the right the list of files inside every folder.

Best Answer

This will do it:
folder = pwd; % The current folder, or else wherever you want.
% Get a list of all files.
fileList = dir(fullfile(folder, '*.*'));
allFileNames = {fileList.name}
% Define what pattern you will need in your filenames.
pattern = 'B10';
numFilesProcessed = 0; % For fun, let's keep track of how many files we processed.

for k = 1 : length(allFileNames)
% Get this filename.
thisFileName = fullfile(fileList(k).folder, allFileNames{k});
% See if it contains our required pattern.
if ~contains(thisFileName, pattern, 'IgnoreCase', true)
% Skip this file because the filename does not contain the required pattern.
continue;
end
% The pattern is in the filename if you get here, so do something with it.
fprintf('Now processing %s\n', thisFileName);
numFilesProcessed = numFilesProcessed + 1; % For fun, let's keep track of how many files we processed.
end
fprintf('Done running %s.m.\nWe processed %d files with %s in the name.\n', ...
mfilename, numFilesProcessed, pattern);