Rename a lot of files

2 vues (au cours des 30 derniers jours)
Cheuk Yin Wong
Cheuk Yin Wong le 15 Août 2022
Commenté : Cheuk Yin Wong le 15 Août 2022
I have a lot of files with names 'Sample_1.csv, Sample_2.csv, Sample_3.csv, ..., Sample_101'. I would like to rename all of them to the format of Sample_xxx.csv, so it becomes like this: 'Sample_001.csv, Sample_002.csv, Sample_003.csv, ..., Sample_101'.
Can anyone help me? Thank you very much.

Réponse acceptée

Walter Roberson
Walter Roberson le 15 Août 2022
@Akira Agata's solution is perfectly usable. But here is a different approach that never converts to numeric and back
dinfo = dif('*.csv');
filenames = {dinfo.name};
new_filenames = regexprep(filenames, {'_(\d)\.', '_(\d\d)\.'}, {'_00$1.', '_0$1.'});
mask = ~strcmp(filenames, new_filenames);
cellfun(@(OLD, NEW) movefile(OLD,NEW), filenames(mask), new_filenames(mask));
The mask part is to avoid trying to movefile() a file to the same name. A file might have the same name after regexprep() if it did not follow the pattern at all, or if it already had 3 or more digits after the '_'
  3 commentaires
Walter Roberson
Walter Roberson le 15 Août 2022
~ is logical negation. The strcmp() is looking for file names that are the same after text replacement; you do not want to process those (besides being inefficient, the movefile() woud complain about moving a file to itself.)
Cheuk Yin Wong
Cheuk Yin Wong le 15 Août 2022
Thank you! It works very well.

Connectez-vous pour commenter.

Plus de réponses (1)

Akira Agata
Akira Agata le 15 Août 2022
How about the following?
fileList = dir('*.csv');
for kk = 1:numel(fileList)
fileNum = extractBetween(fileList(kk).name,'_','.csv');
fileNum = str2double(fileNum);
newFileName = sprintf("Sample_%03d.csv", fileNum);
movefile(fileList(kk).name, newFileName);
end
  1 commentaire
Cheuk Yin Wong
Cheuk Yin Wong le 15 Août 2022
Thank you!

Connectez-vous pour commenter.

Catégories

En savoir plus sur Downloads dans Help Center et File Exchange

Produits


Version

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by