Search code examples
matlabrenamefile-renamebatch-rename

Batch file renaming: How to preserve the order of filename?


I have 1000 images that I want to rename them from 1 to 1000. I found this solution (the most voted answer):

dirData = dir('*.png');         %# Get the selected file data
fileNames = {dirData.name};     %# Create a cell array of file names
for iFile = 1:numel(fileNames)  %# Loop over the file names
newName = sprintf('%04d.png',iFile);  %# Make the new name
movefile(fileNames{iFile},newName);        %# Rename the file
end

But it falls short when the number of digits from the original file name changes. Specifically:

  • After renaming 10 images, the tenth image becomes the number one.
  • Applying the code on 101 images, 101th image becomes the first, 100th becomes the second and the tenth becomes the third.

This affects my dataset because their position is important. The aim is renaming the images from 1,2,3,.... to N. Any way to fix this problem?


My original file names are in the form of 90_AAA_AA_CC and the first number of the above form, varies from 1 to N for N images.

From "dirData.name", the orders for 100 images are as follows:

100,10,11,12, ...
19,1,20,21, ...
29,2,30,31, ...
39,3,40,41, ...
49,4,50,51, ...
59,5,60,61, ...
69,6,70,71, ...
79,7,80,81, ...
89,8,90,91, ... 99,9

Solution

  • The following does what you want. The problem is that the files are currently in lexicographic order, which does not take the whole number into account, but only the separate digits.

    By using a regular expression to get the digits from the filename, and then converting this to a number using str2double, you can keep the correct numbering.

    dirData = dir('*.png');         % Get the selected file data
    fileNames = {dirData.name};     % Create a cell array of file names
    for iFile = 1:numel(fileNames)  % Loop over the file names
        fileName = fileNames{iFile};
        imgNum = str2double(regexp(fileName,'\d*','Match')); % get the img number from the filename
        newName = sprintf('%04d.png',imgNum);  % Make the new name
        movefile(fileName,newName);        % Rename the file
    end