登录论坛

查看完整版本 : 如何在Matlab中解析文件名并重命名


poster
2019-12-10, 20:30
我正在读取.xls文件,然后在其中进行处理,并在程序末尾将其重写。我想知道是否有人可以帮助我解析日期,因为我的输入文件名就像file_1_2010_03_03.csv

我希望我的输出文件是

newfile_2010_03_03.xls

有没有一种方法可以合并到matlab程序中,所以我不必手动编写命令
xlswrite('newfile_2010_03_03.xls',M);每次更改日期,因为我输入带有差异日期的文件
就像file_2_2010_03_04.csv。

也许我不清楚>我正在使用uigetfile输入3个差异文件,格式为file_1_2010_03_03.csv,file_2_2010_03_03.csv,file_3_2010_03_03.csv

现在我正在程序中处理文件并写入4个名称为newfileX_3_2010_03_03.xls,newfileXY_3_2010_03_03.xls,newfileXZ_3_2010_03_03.xls,newfileYZ_3_2010_03_03.xls的输出文件

所以我的日期不是当前日期,但是我需要输入文件中的日期,并将其附加到我的xlswrite的newname上。

所以想知道是否有一种方法可以写一个通用的

xlswrite('xxx'M);每当我输入一个新文件时,它将选择我想要的名称,而不是让我2修改名称“ xxx”

谢谢

谢谢



回答:

看来我误解了“ file_1”,“ file_2”的含义-我认为数字1和2具有某种重要性。

oldFileName = 'something_2010_03_03.csv'; %# extract the date (it's returned in a cell array theDate = regexp(oldFileName,'(\d{4}_\d{2}_\d{2})','match'); newFileName = sprintf('newfile_%s.xls',theDate{1}); 旧版本和解释

我认为所有文件中的日期都相同。所以你的程序会

%# load the files, put the names into a cell array fileNames = {'file_1_2010_03_03.csv','file_2_2010_03_03.csv','file_3_2010_03_03.csv'}; %# parse the file names for the number and the date %# This expression looks for the n-digit number (1,2, or 3 in your case) and puts %# it into the field 'number' in the output structure, and it looks for the date %# and puts it into the field 'date' in the output structure %# Specifically, \d finds digits, \d+ finds one or several digits, _\d+_ %# finds one or several digits that are preceded and followed by an underscore %# _(?\d+)_ finds one or several digits that are preceded and follewed %# by an underscore and puts them (as a string) into the field 'number' in the %# output structure. The date part is similar, except that regexp looks for %# specific numbers of digits tmp = regexp(fileNames,'_(?\d+)_(?\d{4}_\d{2}_\d{2})','names'); nameStruct = cat(1,tmp{:}); %# regexp returns a cell array. Catenate for ease of use %# maybe you want to loop, or maybe not (it's not quite clear from the question), but %# here's how you'd do with a loop. Anyway, since the information about the filenames %# is conveniently stored in nameStruct, you can access it any way you want. for iFile =1:nFiles %# do some processing, get the matrix M %# and create the output file name outputFileX = sprintf('newfileX_%s_%s.xls',nameStruct(iFile).number,nameStruct(iFile).date); %# and save xlswrite(outputFileX,M) end 有关如何使用正则表达式 (http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/f0-42649.html)的更多详细信息,请参见正则表达式 (http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_prog/f0-42649.html) 。另外,您可能对uipickfiles (http://www.mathworks.com/matlabcentral/fileexchange/10867-uipickfiles-uigetfile-on-steroids)替换uigetfile感兴趣。



更多&回答... (https://stackoverflow.com/questions/2456033)