renaming subfolder same as main folder

Hi, iam new in matlab
i have 100 main folder which as 1 subfolder and within the subfolder there are 20 more files. i want to change the name of subfolder same as the main folder and this i want to loop for rest 100 main folder. for eg if main folder is 55555555 and the subfoflder is 12345, i want this to change into 55555555. Also all 100 main folder is within 1 folder.
please help.
thank you

回答 (1 件)

Angelo Yeo
Angelo Yeo 2023 年 7 月 24 日

0 投票

Using movefile can help you. Below is an example script. Please create an empty folder and set the folder as a current folder of MATLAB.
You can run the script below to learn how finding folder names and changing them works.
basepath = pwd;
%% Creating environment
for i_main = 1:100
% creating 100 main folders
mkdir("main" + i_main)
cd(fullfile(basepath, "main"+i_main))
% creating a subfolder named "subfolder1"
mkdir("subfolder1")
% creating 20 files inside subfolder1
cd(fullfile(basepath, "main"+i_main,"subfolder1"))
for i_file = 1:20
fid = fopen("file"+i_file+".txt", "w");
fprintf(fid, "foo");
fclose(fid);
end
cd(basepath)
end
%% find a subfolder and change its name
cd(basepath)
D = dir;
% removing current path or previous path
idx2del = strcmp(string({D.name}), ".") | strcmp(string({D.name}), "..");
D(idx2del) = [];
names_mainfolder = {D.name};
for i_main = 1:length(names_mainfolder)
cd(fullfile(basepath, names_mainfolder{i_main}))
% finding the name of subfolder
D = dir;
idx2del = strcmp(string({D.name}), ".") | strcmp(string({D.name}), "..");
D(idx2del) = [];
% changing the name of subfolder into the main folder
movefile(D.name, names_mainfolder{i_main})
end

カテゴリ

ヘルプ センター および File ExchangeFile Operations についてさらに検索

製品

リリース

R2023a

質問済み:

2023 年 7 月 24 日

回答済み:

2023 年 7 月 24 日

Community Treasure Hunt

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

Start Hunting!

Translated by