Hello, I have a cell array with the list of files I would like to delete. However I would not like to use a for loop to loop through each file to delete it.
Show older comments
Files - A cell array of size 1x3 with file names to be deleted.
Files =
1×3 cell array
{'1.txt'} {'2.txt'} {'3.txt'}
Working Code :
for i = 1:length(Files)
delete(string(Files(i)));
end
However, I would like to write a single line of code without for loop to achieve the same.
Note: Every run of my code can have different number of files to be deleted. So hardcoding with the command
delete 1.txt 2.txt 3.txt
will not be helpful.
Accepted Answer
More Answers (1)
Chuguang Pan
on 8 Mar 2024
maybe you can use cellfun.
Files={'1.txt','2.txt','3.txt'};
cellfun(@delete,Files)
5 Comments
Krishna Ghanakota
on 8 Mar 2024
DGM
on 8 Mar 2024
I doubt that a small loop is going to be meaningfully slow compared to actually making changes to files.
Why not construct a command string and pass that to the system?
% this will probably break if filenames have spaces or other issues
files = {'1.txt','2.txt','3.txt'};
comstr = sprintf(repmat('%s ',[1 numel(files)]),files{:});
system(['rm ' comstr]);
I mean it sure doesn't sound like a great idea, but if that's the road we're on ...
Walter Roberson
on 8 Mar 2024
You need to account for special characters in file names.
% this will probably break if filenames have spaces or other issues
files = {'1.txt','2.txt','3.txt'};
comstr = sprintf(repmat('"%s" ',[1 numel(files)]),files{:});
system(['rm ' comstr]);
Krishna Ghanakota
on 9 Mar 2024
Image Analyst
on 17 Jun 2024
I think rm is a unix command. If you're on Windows, use del.
Categories
Find more on Environment and Settings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!