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

14 visualizaciones (últimos 30 días)
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.

Respuesta aceptada

Guillaume
Guillaume el 26 de Feb. de 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 comentario
Nazar Adamchuk
Nazar Adamchuk el 17 de Jun. de 2021
Editada: Nazar Adamchuk el 17 de Jun. de 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?

Iniciar sesión para comentar.

Más respuestas (1)

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

Categorías

Más información sobre Large Files and Big Data en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by