Rename files with same name as parent folder
1 view (last 30 days)
Show older comments
I have a series of folders with unique names and subfolders containting files within those folders that have the same name:
Folder A
Subfolder 1
File 1
Folder B
Subfolder 1
File 1
Folder C
Subfolder 1
File 1
How do can I loop through all the folders and name the files as parent folder like this:
Folder A
Subfolder 1
File A
Folder B
Subfolder 1
File B
Folder C
Subfolder 1
File C
0 Comments
Accepted Answer
Jan
on 2 Apr 2021
Do the folders "Folder A", "Folder B", ... have the same parent folder? Is there a pattern to recognize "File 1"? The simplification of the example data makes it harder to guess a matching method.
List = dir(fullfile(BaseFolder, '**', '*.*'));
List = List(~[List.isdir]);
Name = {List.name};
[uniqName, ~, iuName] = unique(Name);
for k = 1:numel(uniqName)
fprintf('Name: %s\n', uniqName{k});
match = find(iuName(:).' == k);
for kk = match
Folder = List(kk).folder;
Parts = strsplit(Folder, filesep);
% How to get the wanted part of the folder name now?!
Str = ???;
origFile = fullfile(Folder, List(kk).name);
newFile = fullfile(Folder, sprintf('File %s', Str));
end
end
Due to the missing details I left an important part open.
More Answers (0)
See Also
Categories
Find more on File Operations 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!