how to add a number to the beginning of a filename

30 vues (au cours des 30 derniers jours)
Luke
Luke le 3 Nov 2022
Commenté : Luke le 3 Nov 2022
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

Réponse acceptée

Cris LaPierre
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
fpn = "my/path/1-filename-a.txt"
fpn = "my/path/2-filename-b.txt"
  2 commentaires
Cris LaPierre
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])
ans = 1×2 string array
"my/path/1-filename-a.txt" "my/path/2-filename-b.txt"
Luke
Luke le 3 Nov 2022
This was a very simple solution that worked perfectly, thank you!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by