批处理文件重命名:如何保留文件名的顺序? [英] Batch file renaming: How to preserve the order of filename?

查看:361
本文介绍了批处理文件重命名:如何保留文件名的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有1000张图像,我希望将它们从1重命名为1000.我发现此解决方案(投票最多的答案):

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:

  • 重命名10张图像后,第十张图像成为第一位.
  • 将代码应用于101张图像,第101张图像成为第一张,第100张成为第二张,第十张成为第三张.

这会影响我的数据集,因为它们的位置很重要. 目的是将图像从1,2,3,....重命名为N.有什么办法可以解决此问题?

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?

我的原始文件名采用90_AAA_AA_CC的形式,上述形式的第一个数字对于N张图像从1N不等.

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.

从"dirData.name"开始,获取100张图像的顺序如下:

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

推荐答案

以下内容可满足您的需求.问题在于文件当前按字典顺序排列,该顺序不考虑整数,而仅考虑单独的数字.

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.

通过使用正则表达式从文件名中获取数字,然后使用str2double将其转换为数字,可以保留正确的编号.

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

这篇关于批处理文件重命名:如何保留文件名的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆