renaming a lot of folders automatically by MATLAB

8 次查看(过去 30 天)
It's needed renaming 150 folders depends on numbers of .xls files inside their contents for example inside folder 'a' there are 15 .xls files so needed be renamed to 'a(15)' and in folder 'b' there are 45 .xls file so its needed renaming it to 'b(45)' and so on.but this must happen by using for-loop. by using this function names of folder is gathered : http://www.mathworks.com/matlabcentral/fileexchange/30835-getcontents
but is there any command for renaming a folder?(not file) and how could for-loop be wrote?

采纳的回答

Jan
Jan 2011-9-20
Folders can be renamed using MOVEFILE.
The FOR loop without GETCONTENTS (which I do not know):
ADir = dir(PathName);
ADir = ADir([ADir.isdir]);
AName = {ADir.name};
AName(strncmp(AName, '.', 1)) = [];
for iFolder = 1:numel(AName)
APath = fullfile(PathName, AName{iFolder});
BDir = dir(fullfile(APath, '*.xls'));
newName = sprintf('%s(%d)', AName{iFolder}, numel(BDir));
movefile(APath, fullfile(PathName, newName));
end
  1 个评论
mohammad
mohammad 2011-9-20
great! perfect!
really so much thanks Jan
I appreciate you for your so nice helping. you helped and answered me so much today

请先登录,再进行评论。

更多回答(1 个)

Tigersnooze
Tigersnooze 2011-9-20
Assuming you have the names of all of the folders in question, try something like:
for i = 1:length(directories)
cd(directories(i));
xlsFiles = dir('*.xls');
num_xlsFiles = length(dir.name);
system(['mv ' directories(i) ' ' directories(i) '(' num2str(num_xlsFiles) ')']);
end
That also assumes you're on a Linux/UNIX machine. If you're on Windows, replace "mv" in the system command with "move" (at least I think that's the Windows equivalent). I think that should work.
  3 个评论
Jan
Jan 2011-9-20
f "directories" is a cell string, you need curly braces in the CD and SYSTEM command. You need to convert num_xlsFiles to a string before you can use it to create the new folder name, e.g. by using SPRINTF or NUM2STR.
Matlab's built-in command MOVEFILE works on all platforms and is much faster than forwarding a string to the operating system.
Tigersnooze
Tigersnooze 2011-9-20
Realized the num2str mistake just after posting and remedied that. Also forgot about the movefile command, but listed the syntax for that in my comment. Not sure about the format of "directories," since I made it up, but I suppose it might be a cell array.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by