how to rename multiple file with sequent custom number?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
adhi dermawan
el 29 de Nov. de 2022
Comentada: adhi dermawan
el 12 de Dic. de 2022
dear matlab expert, I have a folder contain multiple txt file as following
1.txt
5.txt
9.txt
13.txt
17.txt
21.txt
25.txt
29.txt
33.txt
37.txt
I want to rename these files and add an underline.So my output should look like this:
2015_001.txt
2015_002.txt
2015_003.txt
2015_004.txt
2015_005.txt
2015_006.txt
2015_007.txt
2015_008.txt
2015_009.txt
2015_010.txt
I tried this code but nothing happened
% Directory of the files
d = 'C:\ZTD\pwv2015';
% Retrieve the name of the files only
names = dir(d);
names = {names(~[names.isdir]).name};
% Calculate the length of each name and the max length
len = cellfun('length',names);
mLen = max(len);
% Exclude from renaming the files long as the max
idx = len < mLen;
len = len(idx);
names = names(idx);
% Rename in a LOOP
for n = 1:numel(names)
oldname = [d names{n}];
newname = sprintf('2015_%s%0*s',d,mLen, names{n});
dos(['rename "' oldname '" "' newname '"']); % (1)
end
0 comentarios
Respuesta aceptada
Rik
el 29 de Nov. de 2022
You may want to consider using movefile instead. That will make this code rely only on Matlab tools, instead of being OS-specific. movefile will also work if you forget to put in the double quotes next time.
The other function you should have been using is fullfile. String concatenation has a habit of making you forget the file separator between folder and file. Your format also does not account for 3 inputs.
oldname = fullfile(d,names{n});
newname = fullfile(d,sprintf('2015_%s%0*s',mLen, names{n}));
3 comentarios
Rik
el 29 de Nov. de 2022
Why did you change so much of the existing code and remove almost all comments? Now your code is more difficult to read and understand.
And why are you using movefile(d,newnames{j},'f')? What exactly do you expect to happen with that syntax?
Your previous code almost did the job, it only needed the correction I pointed out.
Más respuestas (0)
Ver también
Categorías
Más información sobre Whos 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!