changing the name of multiple csv files in a folder
Show older comments
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?
Accepted Answer
More Answers (1)
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
C.G.
on 15 Jan 2021
Matt Gaidica
on 15 Jan 2021
Edited: Matt Gaidica
on 15 Jan 2021
That looks like it's traversing multiple directories? You wouldn't need an embedded loop if you have all your files in one directory (no need for the ii loop). If you need to look in multiple subfolders, I recommend dir2 to simplify things.
Can you provide some info on how the current filename relates to the one you wish to overwrite it with? Give some examples.
C.G.
on 15 Jan 2021
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
Stephen23
on 15 Jan 2021
This SPRINTF call does not use its inputs for anything:
new = sprintf('c0_1f0_1.csv',ii,jj)
Categories
Find more on Loops and Conditional Statements 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!