renaming a lot of folders automatically by MATLAB

2 Ansichten (letzte 30 Tage)
mohammad
mohammad am 20 Sep. 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?

Akzeptierte Antwort

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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Tigersnooze
Tigersnooze am 20 Sep. 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 Kommentare
Jan
Jan am 20 Sep. 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 am 20 Sep. 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.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Introduction to Installation and Licensing finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by