Matlab:按顺序重命名文件夹中的文件

时间:2014-07-02 12:22:10

标签: matlab file renaming

如果文件夹C:\ test \:

中有以下文件

file1.TIF,file2.TIF .... file100.TIF

MatLab可以自动将它们重命名为:

file_0001.TIF,file_0002.TIF,.... file_0100.TIF?

2 个答案:

答案 0 :(得分:2)

一种稍微强大的方法:

dirlist = dir(fullfile(mypath,'*.TIF'));
fullnames = {dirlist.name}; % Get rid of one layer of cell array-ness

[~,fnames,~] = cellfun(@fileparts,fullnames,'UniformOutput',false); % Create cell array of the file names from the output of dir()
fnums = cellfun(@str2double,regexprep(fnames,'[^0-9]','')); % Delete any character that isn't a number, returns it as a vector of doubles
fnames = regexprep(fnames,'[0-9]',''); % Delete any character that is a number

for ii = 1:length(dirlist)
    newname = sprintf('%s_%04d.TIF',fnames{ii},fnums(ii)); % Create new file name

    oldfile = fullfile(mypath,dirlist(ii).name); % Generate full path to old file
    newfile = fullfile(mypath,newname);          % Generate full path to new file

    movefile(oldfile, newfile); % Rename the files
end

虽然这可以容纳任何长度的文件名,但它确实假设文件名中没有数字,而不是最后的计数器。 MATLAB喜欢将东西放入嵌套的单元格数组中,因此我将cellfun合并到了几个地方,以便将内容转换为更易于管理的格式。它还允许我们对一些代码进行矢量化。

答案 1 :(得分:2)

无循环方法 -

directory  = 'C:\test\'; %//' Directory where TIFF images are present
filePattern = fullfile(directory, 'file*.tif'); %//' files pattern with absolute paths
old_filename = cellstr(ls(filePattern)) %// Get the filenames
file_ID = strrep(strrep(old_filename,'file',''),'.TIF','') %// Get numbers associated with each file
str_zeros = arrayfun(@(t) repmat('0',1,t), 5-cellfun(@numel,file_ID),'uni',0) %// Get zeros string to be pre-appended to each filename
new_filename = strcat('file_',str_zeros,file_ID,'.TIF') %// Generate new filenames
cellfun(@(m1,m2) movefile(m1,m2),fullfile(directory,old_filename),fullfile(directory,new_filename)) %// Finally rename files with the absolute paths

修改1:

如果您的文件名为file27.TIFfile28.TIFfile29.TIF等,并且您希望将其重命名为file0001.TIF,{{1} },file0002.TIF等等,试试这个 -

file0003.TIF