如何获取txt文件中具有特定字符串的行号 - matlab

how to get the line number having a specific string in a txt file - matlab

我有一个包含很多内容的 txt 文件,在这个文件中有很多 "include" 单词,我想从之后的所有三行中获取数据。

myFile.txt: “-包括:

-6.5 6.5

sin(x^2)

差异

-包括

-5 5

cos(x^4)

差异

如何在数组中获取这些数据?

根据您的示例(第一个包含最后有 :,第二个没有),您可以使用类似的东西。

fID = fopen('myFile.txt'); % Open the file for reading
textString = textscan(fID, '%s', 'Delimiter', '\n'); % Read all lines into cells
fclose(fID); % Close the file for reading
textString = textString{1}; % Use just the contents on the first cell (each line inside will be one cell)
includeStart = find(contains(textString,'include'))+1; % Find all lines with the word include. Add +1 to get the line after
includeEnd = [includeStart(2:end)-2; length(textString)]; % Get the position of the last line before the next include (and add the last line in the file)
parsedText = cell(length(includeStart), 1); % Create a new cell to store the output
% Loop through all the includes and concatenate the text with strjoin
for it = 1:length(includeStart)
  parsedText{it} = strjoin(textString(includeStart(it):includeEnd(it)),'\n');
  % Display the output
  fprintf('Include block %d:\n', it);
  disp(parsedText{it});
end

结果如下:

Include block 1:
-6.5 6.5
sin(x^2)
diff
Include block 2:
-5 5
cos(x^4)
diff

您可以根据需要调整循环。如果您只想要行号,请使用 includeStartincludeEnd 变量。