Rename of multiple files
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
UWM
el 8 de Abr. de 2021
Comentada: UWM
el 9 de Abr. de 2021
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 comentarios
Respuesta aceptada
Saravanan Sengottuvel
el 8 de Abr. de 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.
Más respuestas (2)
Saravanan Sengottuvel
el 8 de Abr. de 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
el 8 de Abr. de 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 comentarios
Ver también
Categorías
Más información sobre Search Path en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!