list all files in folder that contain the string "abc" inside in matlab

To list all files in a folder that contain a specific string, such as "abc", you can use the dir function to get a list of all files in the directory and then use contains function to check if the file names or contents contain the specific string.

Here's the code:

main.m
% Define the folder path
folder_path = 'C:\MyFolder';

% Get the list of files in the folder
file_list = dir(folder_path);

% Loop through the files and check if the file contains the string "abc"
for i = 1:numel(file_list)
    % Check if the file is a regular file (not a folder)
    if ~file_list(i).isdir 
        % Get the file name
        file_name = file_list(i).name;
        
        % Check if the file name or contents contain the string "abc"
        if contains(file_name, 'abc') || contains(fileread(fullfile(folder_path, file_name)), 'abc')
            % Display the file name
            disp(file_name);
        end
    end
end
645 chars
21 lines

In this code, we first define the folder path (folder_path). Then we use the dir function to get a list of all files in the folder, which is stored in a structure array (file_list).

The for loop iterates through each file in the array. We first check if the file is a regular file (not a folder) using isdir attribute. If the file is a regular file, we get the file name (file_name) and check if it contains the string "abc" using the contains function.

If the file name does not contain the string "abc", we also check the contents of the file using the fileread function, which reads the contents of a file and returns the result as a string. If the contents of the file contain the string "abc", we display the file name using the disp function.

gistlibby LogSnag