How to rename the subfolders

2 views (last 30 days)
Md
Md on 31 Mar 2014
Answered: David Young on 31 Mar 2014
Hey Guys, I have 60 subfolders in a folder. Subfolder names are as follows: A_001, B_001,...Z_001, A_A_001, A_B_001, ....A_Z_001, A_A_A_001, A_A_B_001,.......
I want to rename the sub-folders as follows:
A_001=001,
B_001=002,
............... Z_001=026,
A_A_001=027,
A_B_001=028,
A_Z_001=052
............................................ A_A_A_001=053
Thanks in advance.

Accepted Answer

David Young
David Young on 31 Mar 2014
Please ensure that you make a backup before using this, and check that it is doing exactly what you want. I have not tested it, and you might need to make modifications.
Assuming that the top folder's name is stored as a string in the variable 'top_folder':
d = dir(top_folder);
fnames = {d.name};
% remove pseudo-folders . and ..
dotstart = cellfun(@(s) strcmp(s(1), '.'), fnames);
fnames(dotstart) = [];
maxlen = max(cellfun(@length, fnames));
% pad filenames on front with 'A'
fnames_padded = cellfun(@(s) char(padarray(double(s), [0 maxlen-length(s)], ...
double('A'), 'pre')), fnames, 'UniformOutput', false);
[~, sort_index] = sort(fnames_padded);
fnames_sorted = fnames(sort_index);
for f = 1:length(sort_index)
fname = fnames_sorted{i};
fout = sprintf('%03d', f);
fprintf('Moving %s\n to %s\n', fname, fout);
movefile(fullfile(top_folder, fname), fullfile(top_folder, fout));
end

More Answers (0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!