regexp and string rearrange in text file
조회 수: 2 (최근 30일)
이전 댓글 표시
Rashmil Dahanayake
2014년 7월 16일
댓글: Rashmil Dahanayake
2014년 7월 16일
I have a .txt file which has about 350 lines. The content is the .txt file is in following format
Open loop test -19-06-2014
Current Injection 2 -18-06-2014
Parameter sweep -17-06-2014
Controlled input -16-06-2014
Open loop test 2 -14-06-2014
I need to take the date to the beginning of each line and change the format to yyyy/mm/dd
ie in following format
2014/06/19 Open loop test
2014/06/18 Current Injection 2
Following is the code I have so far
%open file
fid =fopen('lsit2.txt');
C=textscan(fid,'%s','delimiter','\n');
% search for date string and updating the format
for k=1:size(C{1,1},1) % repeat for each line
str=C{1,1}{1};
date = regexp(str, '(\d+)-(\d+)-(\d+)', 'tokens');
newdate_format= sprintf('%s/%s/%s',date{1,1}{3},date{1,1}{2},date{1,1}{1});
end
Could someone help me to modify the code further to
1) To change the position of date
2) save the updated values to the .txt file
댓글 수: 0
채택된 답변
Alfonso Nieto-Castanon
2014년 7월 16일
편집: Alfonso Nieto-Castanon
2014년 7월 16일
something along these lines:
% reads file into cell array
lines = textread('lsit2.txt','%s','delimiter','\n','whitespace','');
% changes format
lines = regexprep(lines, '(.*)-(\d+)-(\d+)-(\d+)','$4/$3/$2 $1');
% saves new file
f = fopen('newfile.txt','wt');
fprintf(f,'%s\n',lines{:});
fclose(f);
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Characters and Strings에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!