批处理文件重命名:如何保留文件名的顺序?
Batch file renaming: How to preserve the order of filename?
我有 1000 张图片,我想将它们从 1 重命名为 1000。我找到了 this solution(投票最多的答案):
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
但当原始文件名的位数发生变化时,它就达不到要求了。具体来说:
- 重命名10张图片后,第十张图片成为第一张。
- 在 101 张图片上应用代码,第 101 张图片成为第一张图片,第 100 张图片成为第二张图片,第十张图片成为第三张图片。
这会影响我的数据集,因为它们的位置很重要。
目的是将图像从 1,2,3,... 重命名为 N。有什么办法可以解决这个问题吗?
我原来的文件名是90_AAA_AA_CC
和上面格式的第一个数字,N张图片从1
到N
不等
从"dirData.name"开始,100张图片的订单如下:
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
下面是你想要的。问题是文件目前是按字典顺序排列的,不考虑整数,只考虑单独的数字。
通过使用正则表达式从文件名中获取数字,然后使用 str2double
将其转换为数字,您可以保持正确的编号。
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
我有 1000 张图片,我想将它们从 1 重命名为 1000。我找到了 this solution(投票最多的答案):
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
但当原始文件名的位数发生变化时,它就达不到要求了。具体来说:
- 重命名10张图片后,第十张图片成为第一张。
- 在 101 张图片上应用代码,第 101 张图片成为第一张图片,第 100 张图片成为第二张图片,第十张图片成为第三张图片。
这会影响我的数据集,因为它们的位置很重要。 目的是将图像从 1,2,3,... 重命名为 N。有什么办法可以解决这个问题吗?
我原来的文件名是90_AAA_AA_CC
和上面格式的第一个数字,N张图片从1
到N
不等
从"dirData.name"开始,100张图片的订单如下:
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
下面是你想要的。问题是文件目前是按字典顺序排列的,不考虑整数,只考虑单独的数字。
通过使用正则表达式从文件名中获取数字,然后使用 str2double
将其转换为数字,您可以保持正确的编号。
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