How to delete files ending with odd number?

7 ビュー (過去 30 日間)
Morgane Flament
Morgane Flament 2018 年 8 月 13 日
コメント済み: Morgane Flament 2018 年 8 月 13 日
Hi,
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 :)

採用された回答

Simon Henin
Simon Henin 2018 年 8 月 13 日
編集済み: Simon Henin 2018 年 8 月 13 日
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
delete(files(i).name);
end
end
  7 件のコメント
Simon Henin
Simon Henin 2018 年 8 月 13 日
No, it could be done within the same loop (with proper accounting). It is just much easier to use a separate loop to make sure nothing gets overwritten.
Simple example.
Imagine:
files = {'file1', 'file2', 'file22', file24', file3'}; % this will happen because of how the dir command organizes the returned files
counter = 1;
----
Each time you go through the loop:
1) file1 will be deleted
2) file2 -> file1
3) file22 -> file2
4) file24 -> file3 (here's the issue. file3 hasn't gone through the loop yet, and thus, will be overwritten!)
---
Hope this clear it up.
Morgane Flament
Morgane Flament 2018 年 8 月 13 日
Thank you very much for your help Simon. It is all clear.
I was also thinking of sorting the files using the function NATSORTFILES: (https://www.mathworks.com/matlabcentral/fileexchange/47434-natural-order-filename-sort)
pth = '/path/to/folder/containing/files/';
files = dir(fullfile(pth,'file*')); % Get the file in the directory
N = natsortfiles({files.name}); % Sort the filename in natural order
for k = 1:numel(N)
fullfile(D,N{k})
end
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.

サインインしてコメントする。

その他の回答 (1 件)

Morgane Flament
Morgane Flament 2018 年 8 月 13 日
@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).
  4 件のコメント
Paolo
Paolo 2018 年 8 月 13 日
@Morgane,
If you wish to delete only files ending with 2,3,4 or 5, change the character set in the regex:
regexp(files(i).name, '[2345]$', 'match')
Morgane Flament
Morgane Flament 2018 年 8 月 13 日
Thank you for your help!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeFile Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by