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

∥☆過路亽.° 提交于 2020-01-24 21:59:24

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/58802830/batch-file-renaming-how-to-preserve-the-order-of-filename

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!