How do I Read a file line by line after a certain character?

2 次查看(过去 30 天)
This is the text file that I have and I want to read the line after the line "ELEM="
That means, whenever matlab will find "ELEM= " it will jump to the next line and read that line, for example, for the first case, it will read
165 -0.21823E-003
Thanks in Advance.
  2 个评论
Maksudul Alam
Maksudul Alam 2022-4-27
Hello, actually it's a very big file and there are some other cherecters as well. So specifying can be little bit difficult.
I just want to do this in a way that, matlab will scan line by line, when will get ELEM=, it will store the datas of the next line in a separate text file. for example, from this picture, it will only read four lines, those starting with 165,277,277,242
can u help me to do this?

请先登录,再进行评论。

回答(1 个)

Walter Roberson
Walter Roberson 2022-4-27
If the file fits into memory, then
filename = 'FileNameGoesHere.ExtensionGoesHere';
S = fileread(filename);
next_lines = regexp(S, '(?<=\^\s*ELEM=[^\n]*\n)[^\n]*', 'lineanchors', 'match');
Note that this will record the entire content of the lines, spaces and all, and will not record the numbers after the ELEM=, and makes no attempt to mark boundaries (which you would need if there are some places where the number of lines after the ELEM= is not exactly the same.)

Community Treasure Hunt

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

Start Hunting!

Translated by