Delete files with specific names

67 ビュー (過去 30 日間)
Tali Leibovich
Tali Leibovich 2016 年 5 月 31 日
編集済み: William R 2021 年 10 月 27 日
Hello
I have a directory with files from the same type with names like:
2016_03_24_09 -0002-0001-00058.dcm
2016_03_24_09 -0002-0001-00059.dcm
2016_03_24_09 -0002-0001-00060.dcm
etc.
Based on the last 5 figures (e.g.,*00060.dcm),
I need to delete every file that ends with a number greater than 276.
Is there a way to do it in a loop?
Thanks,
Tali
  4 件のコメント
Image Analyst
Image Analyst 2016 年 5 月 31 日
You need
for n = 1: size(files, 1)
and, since using ls gives you a character array instead of a cell array, you'll need
delete(strtrim(files(n,:)));
to trim off the extra whitespace. If you use dir() instead of ls(), you don't need to use strtrim().
Tali Leibovich
Tali Leibovich 2016 年 5 月 31 日
it's working!! Thank you so much!!!!

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

採用された回答

Thorsten
Thorsten 2016 年 5 月 31 日
編集済み: Thorsten 2016 年 5 月 31 日
You can get the filenames using
d = dir;
filenames = {d.name};
Loop through the filenames
for i = 1:numel(filenames)
fn = filenames{i};
[num, cnt] = sscanf(fn(find(fn == '-', 1, 'last')+1:end-4), '%d');
if cnt == 1 && num > 276
disp(fn)
end
end
This just displays the files to be deleted. If everything is alright, replace
disp(fn)
with
delete fn
  4 件のコメント
Tali Leibovich
Tali Leibovich 2016 年 5 月 31 日
Thanks!
William R
William R 2021 年 10 月 27 日
編集済み: William R 2021 年 10 月 27 日
This code will not work since
delete fn
will try to delete a file with the name "fn". So the result will be:
Warning: File 'fn' not found.
The right way to do it can be found here.
Or in this example:
delete(fn);

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

その他の回答 (0 件)

カテゴリ

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