Rename of multiple files
7 ビュー (過去 30 日間)
古いコメントを表示
I have many folders and in each I have potentially 480 txt files (“potentially” because in some folders some files are missing) which names changing in ascending order from:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/577042/image.jpeg)
(red number change from 1 to 10, green letter changes from “a” to “x” (24 letters) and blue number is 00 or 30).
A would like to rename file according to the following rule:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/577047/image.jpeg)
So finally, I should get:
1.txt
2.txt
3.txt
4.txt
…
47.txt
48.txt
49.txt
…
480.txt
How it could be done in matlab?
0 件のコメント
採用された回答
Saravanan Sengottuvel
2021 年 4 月 8 日
letter = 'a':'x';
blue1 = '00';
blue2 = '30';
i = 1;
arr = linspace(1, 480, 480);
for id = 1:10 % loop for red number (1 to 10)
for j = 1:24 % loop for green letters (a to x)
if id < 10
f00 = strcat('aaaa00',num2str(id), letter(j),blue1,'.txt');
f30 = strcat('aaaa00',num2str(id), letter(j),blue2,'.txt');
try
movefile(f00, strcat(num2str(arr(i)), '.txt'), 'f')
i = i+1;
movefile(f30, strcat(num2str(arr(i)), '.txt'), 'f') % renaming file
catch
end
i = i+1;
else
f00 = strcat('aaaa0',num2str(id), letter(j),blue1,'.txt');
f30 = strcat('aaaa0',num2str(id), letter(j),blue2,'.txt');
try
movefile(f00, strcat(num2str(arr(i)), '.txt'), 'f')
i = i+1;
movefile(f30, strcat(num2str(arr(i)), '.txt'), 'f') % renaming red number file 10 and above
catch
end
i = i+1;
end
end
end
Hope the above code works for you. It maynot be the optimal solution, but it solves yours problem.
その他の回答 (2 件)
Saravanan Sengottuvel
2021 年 4 月 8 日
Get the name of all files with .txt extension in a directory
files = dir('*.txt');
Run a loop over the collected file names
for id = 1:length(files)
[~, name, ext] = fileparts(files(id).name);
new_filename = strcat(num2str(id), ext);
movefile(files(id).name, new_filename, 'f');
end
Jan
2021 年 4 月 8 日
SrcFolder = 'C:\Your\Folder\';
DestFolder = 'C:\Your\Converted\Output\';
FileList = dir(fullfile(SrcFolder, 'aaaa*.txt')); % Does this catch all wanted files?!
for k = 1:numel(FileList)
Name = FileList(k).name;
CCC = sscanf(Name(5:7), '%d');
R = (Name(8) - 'a') * 2 + (Name(9) == '3') + 1;
Num = (CCC - 1) * 48 + R;
newName = sprintf('%d.txt');
fprintf('%s ==> %s\n', Name, newName); % Does this work as expected?!
Src = fullfile(SrcFolder, Name);
Dest = fullfile(DestFolder, newName)
% copyfile(Src, Dest); % Uncomment this after the code was tested
end
By the way, the file names 1.txt, 2.txt, ... is the topic of many questions in this forum. Usually '0001.txt', '0002.txt', ... is better, because then the alphabetical order equals the numerical order. Use this:
newName = sprintf('%04d.txt');
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Search Path についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!