renaming a lot of folders automatically by MATLAB

20 visualizaciones (últimos 30 días)
mohammad
mohammad el 20 de Sept. de 2011
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?

Respuesta aceptada

Jan
Jan el 20 de Sept. de 2011
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 comentario
mohammad
mohammad el 20 de Sept. de 2011
great! perfect!
really so much thanks Jan
I appreciate you for your so nice helping. you helped and answered me so much today

Iniciar sesión para comentar.

Más respuestas (1)

Tigersnooze
Tigersnooze el 20 de Sept. de 2011
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 comentarios
Jan
Jan el 20 de Sept. de 2011
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 el 20 de Sept. de 2011
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.

Iniciar sesión para comentar.

Categorías

Más información sobre Characters and Strings en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by