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

时间:2018-12-28 12:51:20

标签: matlab textscan

我有一个txt文件,其中包含很多内容,并且在此文件中有很多“ include”一词,之后我希望从所有三行中获取数据。

myFile.txt: “ -include:

-6.5 6.5

sin(x ^ 2)

diff

-包括

-5 5

cos(x ^ 4)

diff”

如何获取数组中的数据?

1 个答案:

答案 0 :(得分:0)

根据您的示例(第一个包括结尾的:,第二个没有),您可以使用类似的内容。

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变量。