How to pass multiple comment style to skip the header of a text file?

조회 수: 14 (최근 30일)
Hi I am pretty new to Matlab, so I need some help. I am trying to read a .txt file by skipping first couple lines (I do not know how many of them I need to skip beforehand). A sample data looks like the following:
<NUMBER OF ZONES 2
<NUMBER OF NODES> 4
<FIRST THRU NODE> 1
<NUMBER OF LINKS> 5
<END OF METADATA>
~ Init node Term node Capacity Length Free Flow Time BPower Speed limit Toll Type;
1 3 1 100 0.00000001 1000000000 1 0 0 1;
1 4 1 100 50 0.02 1 0 0 1;
3 2 1 100 50 0.02 1 0 0 1;
3 4 1 100 10 0.1 1 0 0 1;
4 2 1 100 0.00000001 1000000000 1 0 0 1;
So here, I would like to skip the lines starting with either < or ~. I am using the following codeline:
C = textscan(fid2, '%s' , 'Delimiter', ';', 'CommentStyle' , '<');
And I can skip the first 5 lines. However, I cannot skip the 6th one. I tried to pass multiple commentstyle but it gave an unknown error.
If someone can help me to not read the lines with ~ or <, I'd be glad.
PS: the sample file is easy to see, however, for other files I might not know where exactly the lines that I have to skip are.
Thanks in advance.

채택된 답변

Guillaume
Guillaume 2015년 2월 26일
I don't think textscan supports multiple comment style so you'll have to go a bit more low level:
fid = fopen('somefile', 'rt');
filepos = 0;
tline = fgetl(fid);
%read lines until end of file is reached (tline empty) or not a comment
while ~isempty(tline) & any(strncmp(tline, {'<', '~'}))
filepos = ftell(fid);
tline = fgetl(fid);
end
%the last line read was not a comment, rewind to its beginning
fseek(fid, filepos, 'bof');
%now use textscan, comments are already skipped
C = textscan(fid2, '%s' , 'Delimiter', ';', ');
fclose(fid);
  댓글 수: 1
Nazar Adamchuk
Nazar Adamchuk 2021년 6월 17일
편집: Nazar Adamchuk 2021년 6월 17일
Hi this script ist not right. Why ist was markes as "accepted?
For expample, line five has tio have && and not &. In the same line: what sort of the command "strncmp" is?
"fid2 in the 10th line ist not defined!
Can you redo your solution?

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

추가 답변 (1개)

kukushkin
kukushkin 2015년 2월 26일
Thank you very much for your time to post this code. I benefit a lot and learned new things!

카테고리

Help CenterFile Exchange에서 Large Files and Big Data에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by