Delete files with a specific string
51 views (last 30 days)
In my directory I have 1000's of files, however some files are not needed and they all have the string "Yes_" in their file names, is there an easy way to delete all files that contain this phrase in their name?
Image Analyst on 17 Jan 2022
% Specify the folder where the files live.
myFolder = pwd; % or wherever . . . 'C:\Users\yourUserName\Documents\My Pictures';
% Check to make sure that folder actually exists. Warn user if it doesn't.
errorMessage = sprintf('Error: The following folder does not exist:\n%s\nPlease specify a new folder.', myFolder);
myFolder = uigetdir(); % Ask for a new one.
if myFolder == 0
% User clicked Cancel
% Get a list of all files in the folder with the desired file name pattern.
filePattern = fullfile(myFolder, '*.*'); % Change to whatever pattern you need.
theFiles = dir(filePattern);
for k = 1 : length(theFiles)
baseFileName = theFiles(k).name;
fullFileName = fullfile(theFiles(k).folder, baseFileName);
fprintf(1, 'Now checking %s\n', fullFileName);
% Now do whatever you want with this file name,
% such as deleting it.
if contains(baseFileName, 'Yes_', 'IgnoreCase', true)
fprintf(1, ' Now deleting %s\n', fullFileName);
recycle on % Go to recycle bin
Adapted from the FAQ: