MATLAB: Re-naming Text files in many folders using matlab

fileMATLABtext file

Dear all
i have many folders, where every folder contain text files, i need to parse the whole folders and then re-naming exist files to name of parent folder along with its names as in follow:
for example in folder1 where text files are ={ text1.txt, name.txt, vbar.txt, ….etc} hope to be = { folder1-text1.txt, folder1-name1.txt, etc…}
thanks for any suggestion

Best Answer

projectdir = 'name of main directory goes here';
dinfo = dir(projectdir);
dinfo(~[dinfo.isdir]) = []; %remove non-folders
dinfo(ismember({dinfo.name}, {'.', '..'}) = []; %remove . and .. directories
num_subdir = length(dinfo);
for S = 1 : num_subdir
this_subdir = dinfo(S).name;
subdinfo = dir( fullfile(projectdir, this_subdir, '*.txt') );
num_subfile = length(subdinfo);
for F = 1 : num_subfile
this_file = subdinfo(F).name;
old_file = fullfile( projectdir, this_subdir, this_file );
new_file = fullfile( projectdir, [this_subdir '-' this_file] );
try
rename(old_file, new_file);
catch ME
fprintf('Failed to rename "%s" to "%s"\n', old_file, new_file );
end
end
end