how to add a number to the beginning of a filename

10 views (last 30 days)
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

Accepted Answer

Cris LaPierre
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
fpn = "my/path/1-filename-a.txt"
fpn = "my/path/2-filename-b.txt"
  2 Comments
Luke
Luke on 3 Nov 2022
This was a very simple solution that worked perfectly, thank you!

Sign in to comment.

More Answers (0)

Categories

Find more on Programmatic Model Editing in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by