读入txt文件-Matlab Line Extraction with Logic

Reading in txt File -Matlab Line Extraction with Logic

目前难以阅读具有下述总体布局的 .txt 文件:

(.txt 文件遵循此总体布局 "N" 次)

-----------------------------------
Header Info 1
Desired data 1
More data
More data
-----------------------------------
Header Info 2
Desired data 2
More data
-----------------------------------
Header Info 3
Desired data 3
More data
More data
More data
More data
----------------------------------
Header Info N
Desired data N
More data
More data
More data
CLOSING DATA LINE

我想只提取 "Desired data" 和最后的 "CLOSING DATA LINE" 但问题是中间有不同的 "More data" 行禁止简单的逐行 -线提取模式。这些 "More data" 行可以有 0-000 行...

我确实知道我想要的数据在每个“----------------”下面的 2 行并且想知道是否有某种方法可以 "detect" a "--------" 并在其下方执行 2 行的行提取。此外,为了获得最后一行,尝试实现逻辑以提取之前的那一行。

我曾想过用 fgetl 遍历每一行,并让 if 语句使用看起来很漂亮的 strcmpare 捕获“----------”"brute force-ish"。有什么轻量级或高效的解决方案吗?

您可以尝试以下示例,假设您的文本文件名为 a.txt:

% open and read file
f = fopen('a.txt');
d = textscan(f, '%s', 'Delimiter', '');

% since d is a cell containing another cell array
dd = d{1};

% index of '-------' lines
myidx = find(cellfun(@(DD)all(ismember(DD, '-')), dd));

% output data
mydata = [dd(myidx + 2); dd(end)];

% close file
fclose(f);

如果第 dd{k} 行包含所有 -,则使用 all(ismember(dd{k}, '-')) 为您提供 1,否则为 0。然后对其执行cellfun得到1和0值的数组,其中1代表所有-的那一行。最后,使用 find 获取 1 个值的索引。