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

files = ls('*.dcm'); % list of files with .dcm extension
for n = 1:N
ind1 = strfind(files(n,:), '-'); % indicies of the '-' char
ind2 = strfind(files(n,:), '.'); % index of '.'
str = files(n,ind1(end)+1:ind2-1);% extract the numeric string
if str2num(str) > 276
delete(files(n,:)); % delete if greater than 276
end
end
Tali Leibovich
Tali Leibovich 2016년 5월 31일
Hi John
Thank you so much for your quick response!
I'm trying it now and get this error for the first line (for n=1:N):
Error using :
For colon operator with char operands, first and last operands must be char.
Have I done something wrong?
Thanks again so much!
Tali
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일

1 개 추천

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일
Hi Thorsten
Thank you so much for your response!
I tried to use it, and changed the function from disp to delete
But for some reason I can still see the files in the folder.
Is there anything that I'm missing?
Thank you so much again!
Tali
The files have to be in the same folder. Otherwise you'll have to prepend the folder with the fullfile() function.
Also, you might want to put
recycle on;
before the code to send it to the recycle bin instead of losing it forever.
And if you have the file manager open, you might need to refresh the view to see the changes.
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개)

카테고리

도움말 센터File Exchange에서 File Operations에 대해 자세히 알아보기

질문:

2016년 5월 31일

편집:

2021년 10월 27일

Community Treasure Hunt

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

Start Hunting!

Translated by