Rename files with same name as parent folder

1 view (last 30 days)
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

Accepted Answer

Jan
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.
  3 Comments
Jan
Jan on 8 Apr 2021
Edited: Jan on 8 Apr 2021
Do you find a solution for
% How to get the wanted part of the folder name now?!
already? Can you find the needed information in the variable Parts ? If not, please provide the available details.
Nadeau Hahne
Nadeau Hahne on 8 Apr 2021
I did! You definitely started me on the right track.
% Use cd to establish BaseFolder
BaseFolder = 'Folder Path';
% Paste folder with name to be changed
ContainingFolder = 'Containing Folder';
% Paste file name to be changed
OldFile = 'File Name';
% Create Struct with folder information
List = dir(BaseFolder)
% Confirms contents that are directories only
ListFolders = List([List(:).isdir]);
% Gets rid of folders above BaseFolder ('.', '..')
ListFolders = ListFolders(~ismember({ListFolders(:).name},{'.','..'}));
Name = {ListFolders.name};
[uniqName, ~, iuName] = unique(Name);
% Loop through all the folders
for k = 1:numel(uniqName);
match = find(iuName(:).' == k);;
for kk = match;
Folder = ListFolders(kk).folder;
Str = fullfile(Folder, uniqName{k}, ContainingFolder, OldFile);
newFile = fullfile(Folder, uniqName{k}, ContainingFolder, uniqName{k});
movefile(Str, newFile)
% If you want to change the Containing Folder name use this for instead
% movefile(Str, fullfile(Str,uniqName{k}))
end
end

Sign in to comment.

More Answers (0)

Categories

Find more on File Operations in Help Center and File Exchange

Products


Release

R2020b

Community Treasure Hunt

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

Start Hunting!