필터 지우기
필터 지우기

I need to read and rewrite only certain lines of a text file.

조회 수: 1 (최근 30일)
Joseph
Joseph 2013년 6월 20일
I have a text file full of data. The file has multiple data sets, often more that 100. I only need the last 2 data points in each set however. So for example I currently have:
Data 1
C 2 3 5
C 2 3 7
C 2 2 9
C 3 10 -7
Data 2
C 2 8 9
C -9 -3 7
C 4 -2 14
C 0 0 0
And I need to write a text file that reads.
2 2 9
3 10 -7
4 -2 14
0 0 0
I currently have code that removes the first data label, the first two lines of the data, and the side "C" labels but I am unsure how get this to loop for the rest of the data. My code is as follows.
fid = fopen('Test_Data_2.txt', 'rt');
datacell = textscan(fid, '%*s %f %f %f', 'HeaderLines', 3, 'CollectOutput', 1);
fclose(fid);
datacell{1};
dlmwrite('md_msd.out', datacell{1}, 'delimiter', '\t', ...
'precision', 6)
I just need to get rid of any unwanted data after the first data set. Can anybody help me?
  댓글 수: 1
Walter Roberson
Walter Roberson 2013년 6월 20일
Are there a fixed number of lines for each dataset? Do the lines that mark the beginning of the next dataset always start with 'Data' ?

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
Jan 2013년 6월 20일
Str = fileread('Test_Data_2.txt');
CStr = regexp(Str, '\n', 'split');
Match = strcnmp(CStr, 'Data', 4);
Index = find(Index);
Match(Index + 1) = true;
Match(Index + 2) = true;
CStr(Match) = []; % Remove the 'Data x' and the two following lines
CStr = strrep(CStr, 'C ', ''); % Remove leading 'C '
FID = fopen('Test_Data_2_out.txt', 'w');
if FID == -1, error('Cannot open file for writing'); end
fprintf(FID, '%s\n', CStr{:});
fclose(FID);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by