How to delete files ending with odd number?

21 views (last 30 days)
I would like to delete each files having its filename ending by an odd number. Example: file0 file1 file2 file3 file4 After: file0 file2 file4
Thank you for your help :)

Accepted Answer

Simon Henin
Simon Henin on 13 Aug 2018
Edited: Simon Henin on 13 Aug 2018
You could looop through all the files and delete ones that have an odd number using regexp, regular expression search
files = dir('*'); % find all files in current directory
for i=1:length(files),
fileno = str2double(cell2mat(regexp(files(i).name, '[0-9]{1,}', 'match')));
if mod(fileno, 2) == 1, % check if fileno modulo 2 == 1
Morgane Flament
Morgane Flament on 13 Aug 2018
Thank you very much for your help Simon. It is all clear.
I was also thinking of sorting the files using the function NATSORTFILES: (
pth = '/path/to/folder/containing/files/';
files = dir(fullfile(pth,'file*')); % Get the file in the directory
N = natsortfiles({}); % Sort the filename in natural order
for k = 1:numel(N)
And then I add the loops. Do you think it is a good idea?
Again, thank you for your time, it helps me a lot.

Sign in to comment.

More Answers (1)

Morgane Flament
Morgane Flament on 13 Aug 2018
@Simon Henin, do you think I can use your code as well, to delete each file ending with number 2, 3, 4, 5, but not with 0 and 1 let's say? (so no function with odd/even number in this case, I would like to delete the file based on its number at the end of the filename).

Sign in to comment.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!