Removing subfolders with same name
1 view (last 30 days)
Show older comments
I have a series of folders with unique names but the sub folders have the same names:
Folder 1
Subfolder A
Subfolder B
Folder 2
Subfolder A
Subfolder B
How do I loop through all the folders to delete all of the Subfolder B's?
2 Comments
Accepted Answer
Jan
on 2 Apr 2021
BaseFolder = 'C:\Parent\Folder'
List = dir(fullfile(BaseFolder, '**', 'Folder B'));
List = List([List.isdir]);
List(strcmp({List.name}, '..')) = [];
for k = 1:numel(List)
disp(List(k).folder)
% Check this twice before you uncomment this:
% rmdir(List(k).folder);
end
4 Comments
Jan
on 3 Apr 2021
The '..' is a char vector. DIR replies '.' as pointer to the current folder and '..' for the parent folder.
List(strcmp({List.name}, '..')) = [];
To find out, what this does, evaluate it in parts:
{List.name}
strcmp({List.name}, '..')
List(strcmp({List.name}, '..'))
The " = []" is Matlab's method to delete elements. The complete line removes all elements of the List, if their name is '..' .
If the folders are not empty, ue the 's' flag:
rmdir(List(k).folder, 's');
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!