Rename of multiple files
3 views (last 30 days)
Show older comments
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:
(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:
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 Comments
Accepted Answer
Saravanan Sengottuvel
on 8 Apr 2021
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.
More Answers (2)
Saravanan Sengottuvel
on 8 Apr 2021
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
on 8 Apr 2021
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 Comments
See Also
Categories
Find more on Search Path in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!