MATLAB Answers

changing the name of multiple csv files in a folder

34 views (last 30 days)
C.G.
C.G. on 15 Jan 2021
Commented: Stephen Cobeldick on 15 Jan 2021
I have a folder containing 3000 csv files. All of these are named in the format: cor0.1 sc10 fc0.1_0.csv.
I want to change the name of all of these files to c0_1f0_1_0.csv.
Is there a way i can write a loop to do this for me?

  0 Comments

Sign in to comment.

Accepted Answer

Mathieu NOE
Mathieu NOE on 15 Jan 2021
hello
this is a first attempt
I prefered to create the renamed copies in a separate folder
also my code will probably need some upgrade as I don't know how the numberring inside your filenames can evolve among your 3000 files
d = dir('*.csv')
dir_out = [cd '\out']
for ci = 1:numel(d)
filename = d(ci).name;
ind_und = strfind(filename,'_'); % search underscores
ind_dot = strfind(filename,'.'); % search dots
ind_f = strfind(filename,'f'); % search "f"
new_filename = [filename(1) filename(ind_dot(1)-1) '_' filename(ind_dot(1)+1) filename(ind_f ),...
filename(ind_dot(2)-1) '_' filename(ind_dot(2)+1) '_' filename(end-4:end)];
copyfile(filename,fullfile(dir_out,new_filename));
end

  9 Comments

Show 6 older comments
Stephen Cobeldick
Stephen Cobeldick on 15 Jan 2021
Rather than fragile indexing, it better to use fileparts to split the filename and file extension:

Sign in to comment.

More Answers (1)

Matt Gaidica
Matt Gaidica on 15 Jan 2021
Edited: Matt Gaidica on 15 Jan 2021
csvPath = '/path/to/files';
filelist = dir(fullfile(csvPath,'*.csv'));
for iFile = 1:numel(fileList)
thisFile = fullfile(csvPath,fileList(iFile).name);
movefile(thisFile, strrep(thisFile,'old','new'));
end
This is just psuedocode. I don't quite see how you're mapping the old filename to the new one, so I just placed a string replace function in the loop. If you need help on that piece, please post more details.
See:

  6 Comments

Show 3 older comments
Matt Gaidica
Matt Gaidica on 15 Jan 2021
Mathieu gave a suggestion below. I find strrep to the most readable. Sprintf would also work if you are using the iteration variable.
thisFile = strrep(thisFile,' ',''); % remove single spaces
thisFile = strrep(thisFile,'.',''); % remove period
thisFile = strrep(thisFile,'sc10',''); % remove sc10
If you have multiple spaces, perhaps see here.
Stephen Cobeldick
Stephen Cobeldick on 15 Jan 2021
This SPRINTF call does not use its inputs for anything:
new = sprintf('c0_1f0_1.csv',ii,jj)
C.G.
C.G. on 15 Jan 2021
I understand sprintf, but i am struggling to write a loop to do this.
I have started using Mathieu's code below, but this reaches 10 iterations and stops even though it identifies 3001 csv's

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by