2010-03-16 1 views
1

.xls 파일을 읽은 다음 내부에서 처리하고 프로그램 끝에서 다시 쓰고 있습니다. 누군가가 내 입력 파일 이름과 날짜 을 구문 분석하는 데 도움이 될 수 있다면 궁금 것은 방식이 file_1_2010_03_03.csvMatlab에서 파일 이름을 파싱하고 이름을 바꾸는 방법

처럼 만 내 OUTPUTFILE이

newfile_2010_03_03.xls

되고 싶어 matlab 프로그램에 통합하여 명령을 직접 쓸 필요가 없습니다.
xlswrite ('newfile_2010_03_03.xls', M); 을 입력하고 날짜를 변경하십시오. 차이 날짜가
인 파일을 file_2_2010_03_04.csv와 같이 입력하십시오.

아마 내가

file_3_2010_03_03.csv 지금 난 내 프로그램 내에서 파일을 처리하고 4를 쓰고 있어요, 나는 형식 file_1_2010_03_03.csv, file_2_2010_03_03.csv에 입력 3 개은 diff 파일을 uigetfile 사용하고 > 명확하지 않았다 이름 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는'

+1

그래서 새 파일 이름에 "file_"다음에 정수를 포함 하시겠습니까? – gnovice

+0

내 출력의 날짜가 같은 날짜를 제외하고는 완전히 다른 이름을 가지고 있습니다. – Paul

+1

또한 입력 한 3 개의 파일에서 * 4 * 파일이나 * 12 * 파일을 출력합니까? – gnovice

답변

1

'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 
%# _(?<number>\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,'_(?<number>\d+)_(?<date>\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 

사용 방법에 대한 자세한 내용은 regular expressions을 참조하십시오.또한 uigetfile을 (를) 대체하기 위해 uipickfiles (이)가 유용 할 것입니다.

+0

'd +'는 무엇을합니까 ?? '+'는 무엇을합니까? – Paul

+0

@Paul : 좀 더 자세한 설명을 추가했습니다. 희망 사항은 상황을 더 분명하게 만듭니다! – Jonas

+0

간단하게 만들 수 있습니다. 나는 사용합니다. [a, patha] = uigetfile ({ '*. csv'}, '파일 선택', 'c : \ Data'); File_selected = a file1 = [patha]; oldFileName = a; % NEWFILENAME = regexprep (oldFileName, 'pwr_avg_ \ D + _', 'newfile_') 나는이 작업을 수행 할 때 가 나에게 내 초기 파일 이름 이었다로 newfile_03_03.csv 가 왜 2010 년을 그리워 않았다으로 새 파일 이름을 제공합니다 file_1_2010_03_03.csv – Paul

0

당신이 구축하려는 경우 이해가 안 파일 이름은 날짜를 기준으로하거나 아닙니다. 당신은 당신이 읽은 파일의 이름을 변경하려는 경우, 당신은이 작업을 수행 할 수 있습니다

filename = 'file_1_2010_03_03.csv'; 
newfilename = strrep(filename,'file_1_', 'newfile_'); 
xlswrite(newfilename,M) 

UPDATE :

파일 이름에서 날짜를 구문 분석 :

dtstr = strrep(filename,'file_1_',''); 
dtstr = strrep(dtstr,'.csv',''); 
DT = datenum(dtstr,'yyyy_mm_dd'); 
disp(datestr(DT)) 

구축하기 위해 파일 이름 (예 : 오늘) :

+0

나는 파일을 변경 한 후 그 번호를 놓쳤습니다. 다른 솔루션으로 이동하십시오. – yuk

0

UIGETFILE에서 3 개 개의 파일 모두 이름에 같은 날짜가있는 경우, 당신은 단지 (당신이 3 개 파일에서 모든 데이터를 처리 한 후) 다음을 수행 할 그들 중 하나를 사용할 수 있습니다

fileName = 'file_1_2010_03_03.csv';   %# One of your 3 file names 
data = textscan(fileName,'%s',...   %# Split string at '_' and '.' 
       'Delimiter','_.'); 
fileString = sprintf('_%s_%s_%s.xls',..  %# Make the date part of the name 
        data{1}{(end-3):(end-1)}); 
xlswrite(['newfileX' fileString],dataX);  %# Output "X" data 
xlswrite(['newfileXY' fileString],dataXY); %# Output "XY" data 
xlswrite(['newfileXZ' fileString],dataXZ); %# Output "XZ" data 
xlswrite(['newfileYZ' fileString],dataYZ); %# Output "YZ" data 

TEXTSCAN 함수는 '_' 또는 '.' 문자가 발생하는 지점에서 이전 파일 이름을 구분하는 데 사용됩니다. 그런 다음 함수 SPRINTF을 사용하여 날짜 조각을 다시 배치합니다.

+0

출력 파일에 .csv 파일이 없습니까? 위 코드를 사용하면 새 파일을 얻게됩니다. newfileXY_2010_03_03.csv.xls – Paul

+0

@Paul : 코드에서 오타가 수정되었습니다. 그것은 지금 당신이 원하는 방식으로 작동해야합니다. – gnovice

+0

이전의 ans가 더 마음에 들었습니다. P – Paul

0

아마도 이러한 파일은 모두 어딘가에 디렉토리에 있으며 일괄 적으로 처리하려고합니다. 이와 같은 코드를 사용하여 특정 디렉토리의 파일을 읽고 'csv'로 끝나는 파일을 찾을 수 있습니다. 그렇게하면 새 파일을 처리하려는 경우 코드를 전혀 변경할 필요가 없습니다. 디렉토리에 파일을 놓고 프로그램을 실행하면됩니다.

extension = 'csv'; 

files = dir(); % e.g. use current directory 

% find files with the proper extension 
extLength = length(extension); 
for k = 1:length(files) 
    nameLength = length(files(k).name); 
    if nameLength > extLength 
     if (files(k).name((nameLength - extLength + 1):nameLength) == extension) 
      a(k).name 
      % process file here... 
     end 
    end 
end 

조나스가 제안한 regexp 처리를 통합하면보다 컴팩트하게 만들 수 있습니다.