'How can I cut a string in multiple .csv filenames while keeping the starting strings in Matlab?
This is the sample of the .csv files I have in a folder 84 files
W17F07mylatest0_077004_20220214_122524_a
W17F07mylatest0_077005_20220214_122530_a
W17F07mylatest0_077006_20220214_122537_a
W17F07mylatest0_077007_20220214_122543_a
I would like to remove "_20220214_122524_a" part of each file to get:
W17F07mylatest0_077004
W17F07mylatest0_077005
W17F07mylatest0_077006
W17F07mylatest0_077007
I tried using
movefile('W17F07mylatest0_077005_20220214_122530_a.csv','W17F07mylatest0_077005.csv')
or
newStr = extractBefore(W17F07mylatest0_077005_20220214_122530_a.csv, "_2022");
name_join = strcat(newStr, ".csv");
I could only change for a single file per time, but needs a code to loop for all the files in the folder.
Thanks for any assistance.
Solution 1:[1]
Assume that the underline position is not changing, maybe use this
fname='W17F07mylatest0_077004_20220214_122524_a';
fnamesplit=split(fname,'_');
fnamej=strjoin(fnamesplit(1:2),'_');
fnamej =
'W17F07mylatest0_077004'
For batch processing:
filedir=dir('.\*.csv');
for ifd=1:length(filedir)
fname=filedir(ifd).name;
fnamesplit=split(fname,'_');
fnamej=strjoin(fnamesplit(1:2),'_');
movefile(filedir(ifd).name,fnamej)
end
I don't have actual files to test these. Please let me know if you get into any errors.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |