how to add a number to the beginning of a filename
30 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Thank you in advance, I have been trying to figure out a way to do this for awhile and keep getting stuck. I have a folder with an arbitrary amount of files, and I want to just add numbers incrementally to the beginning of the filename. For example:
"filename-a.txt" --> "1-filename-a.txt"
"filename-b.txt" --> "2-filename-b.txt"
Thisis as far as I have gotten, but I realize with this I am just changing a known string to something else:
for k = 1:numel(filepath)
[~,old,ext] = fileparts(S(k).name);
new = strrep(old,'filename-a','1-filename-a');
fpo = fullfile(locationfolder,[old,ext]);
fpn = fullfile(locationfolder,[new,ext]);
movefile(fpo,fpn,'f');
end
0 commentaires
Réponse acceptée
Cris LaPierre
le 3 Nov 2022
Not knowing what all your variables, are, I think I would simplify to this.
for k = 1:length(S)
fpo = fullfile(locationfolder,S(k).name)
fpn = fullfile(locationfolder,k + "-" + S(k).name);
movefile(fpo,fpn,'f');
end
Just to show you what fpn looks like, see this simple example.
locationfolder = "my/path/";
S(1).name = "filename-a.txt";
S(2).name = "filename-b.txt";
for k = 1:length(S)
fpn = fullfile(locationfolder,k + "-" + S(k).name)
end
2 commentaires
Cris LaPierre
le 3 Nov 2022
You could also generate all the new file names outside of the loop. This might not get you anything, though, as movefile only accepts scalar inputs, meaning you'd still have to rename the files one at a time.
locationfolder = "my/path/";
S(1).name = "filename-a.txt";
S(2).name = "filename-b.txt";
fullfile(locationfolder,(1:length(S)) + "-" + [S(:).name])
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!