how to add a number to the beginning of a filename
10 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Cris LaPierre
on 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
More Answers (0)
See Also
Categories
Find more on Programmatic Model Editing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!