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

14 views (last 30 days)
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.

Accepted Answer

Guillaume
Guillaume on 26 Feb 2015
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 Comment
Nazar Adamchuk
Nazar Adamchuk on 17 Jun 2021
Edited: Nazar Adamchuk on 17 Jun 2021
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?

Sign in to comment.

More Answers (1)

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

Categories

Find more on Large Files and Big Data in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!