How to delete repeating header lines from text file

2 次查看(过去 30 天)
I have a text file consisting of a recurring sequence, made up of 4 header lines followed by 37 lines of data, then another 4 header lines, and so on (see attached txt file). One complication is that each set of headers is slightly different since it incorporates varying numbers. I want to delete all of these header lines and be left with the remaining data.

采纳的回答

Star Strider
Star Strider 2016-9-15
There is no end-of-file in the file you posted. Normally, I would use this code:
fidi = fopen('Bruno Rodriguez a160628.dat','r');
k1 = 1;
while ~feof(fidi)
data(k1) = textscan(fidi, repmat('%f',1,20), 'HeaderLines',4, 'CollectOutput',1, 'EndOfLine','\r\n');
fseek(fidi,0,0);
k1 = k1 + 1;
end
With the file you posted, it is necessary to detect the last record differently. I used fgetl and strfind, copying part of the last header manually to the strfind call.
This works:
fidi = fopen('Bruno Rodriguez a160628.dat','r');
lastrecord = 0; % Initialise ‘lastrecord’
k1 = 1; % Initialise Counter
while ~feof(fidi)
data(k1) = textscan(fidi, repmat('%f',1,20), 'HeaderLines',4, 'CollectOutput',1, 'EndOfLine','\r\n');
if lastrecord % If Previous Was ‘lastrecord’, Stop
break
end
fseek(fidi,0,0); % Restart At New Position
firstline = fgetl(fidi); % Read First Line
lastrecord = strfind(firstline, 'SJSU_Sodar_DiabloCanyon 06/28/2016 23:50:00'); % Find Last Record Section
fseek(fidi, -1, 0); % Back Up One Line So ‘textscan’ Will Read It
k1 = k1 + 1; % Increment Counter
end

更多回答(1 个)

Walter Roberson
Walter Roberson 2016-9-15
Is the "SJSU" always going to be the same? If so then you could perhaps take advantage of the CommentStyle of textscan()
  1 个评论
Bruno Rodriguez
Bruno Rodriguez 2016-9-15
Yes, the SJSU will always be the same. Is there a way to consistently delete the 3 lines after that too? I don't think I can make the assumption that the following 3 lines will start the same way each time.

请先登录,再进行评论。

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by