how to open an external text file, identify two strings and save the lines of the text file where the two strings appear

1 回表示 (過去 30 日間)
Hi,
I would like to open an external text file, identify two strings, for example "Pattern1" and "Pattern2" and save in two variables, line1 and line2, the number of the line of the text file where "Pattern1" and "Pattern2". I am attaching the text file. In this example line1=12 and line2=24
I thank you in advance,
Best regards,
Hugo

採用された回答

Mathieu NOE
Mathieu NOE 2021 年 3 月 12 日
hello Hugo
see below
Filename = 'sample_text.txt';
[Pattern1_line, Pattern2_line] = extract_data(Filename);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Pattern1_line, Pattern2_line] = extract_data(Filename)
fid = fopen(Filename);
tline = fgetl(fid);
% initialization
k = 0;
p = 0;
q = 0;
Pattern1_line = 0;
Pattern2_line = 0;
while ischar(tline)
k = k+1; % loop over line index
% retrieve line Date/Time
if contains(lower(tline),'pattern1') % lower make matlab not case sensitive
Pattern1_line = k;
end
% retrieve line Date/Time
if contains(lower(tline),'pattern2') % lower make matlab not case sensitive
Pattern2_line = k;
end
tline = fgetl(fid);
end
fclose(fid);
end
  1 件のコメント
Jan
Jan 2021 年 6 月 29 日
Note: contains has an option to ignore the case. This is more efficient than lower() of the input.

サインインしてコメントする。

その他の回答 (2 件)

Jan
Jan 2021 年 6 月 29 日
S = fileread('sample_text.txt');
C = strsplit(S, '\n');
Pattern1_line = find(contains(C, 'Pattern1', 'IgnoreCase', true));
Pattern2_line = find(contains(C, 'Pattern2', 'IgnoreCase', true));

Hugo
Hugo 2021 年 3 月 12 日
Dear Mr. Mathieu,
Thank you for your help. Unfortunately, your solution does not work on my end. Do you have other suggestions?
  3 件のコメント
Hugo
Hugo 2021 年 3 月 15 日
Hi,
I don't get any error. I just don't get any output file with the data I want to filter. Do you have any other suggestion?
Mathieu NOE
Mathieu NOE 2021 年 3 月 16 日
hello
you should get the two variables in your workspace
that's what the line :
[Pattern1_line, Pattern2_line] = extract_data(Filename);
does.
proof :
I got in my workspace :
Pattern1_line = 12
Pattern2_line = 24
Now if you want to save it in a output file, I didn't code it but I suppose you know how to do it

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeEntering Commands についてさらに検索

製品


リリース

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by