How to determine the line-number in a file that contains specific statements

15 ビュー (過去 30 日間)
Homayoon
Homayoon 2016 年 3 月 24 日
編集済み: KSSV 2016 年 3 月 24 日
Dear All,
I do have a file that has a line starting with the following statement:
I Need This Line
What I need is to locate the line number of this line and fgetl of the file from beginning to this line(including this line). What should I do? Basically the problem here is the location of the wanted line varies from one file to another so that it makes way too difficult for me to obtain the information I want. Please be advised that I used fopen command to open my input file. Thank you so much
  7 件のコメント
Homayoon
Homayoon 2016 年 3 月 24 日
no in fact I got what you suggested but does not work
I used this code
for c=1:19
line=fgets(fid)
if (strcmp(line,'I Need This Line')==1)
%take this c
end
end
But it reads the content of all of my lines as -1 which I do not know why
KSSV
KSSV 2016 年 3 月 24 日
You are not opening the file properly....what is fid value? It shall be +ve. Cross check the value of line with your file.

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

採用された回答

KSSV
KSSV 2016 年 3 月 24 日
編集済み: KSSV 2016 年 3 月 24 日
Homayoon you may try the following code with the attached txt file.
file = 'Junk.txt' ;
fid = fopen(file,'r') ;
str = 'I Need This Line' ;
for c=1:13
line=strtrim(fgets(fid)) ;
if strcmp(line,str)
iwant = c ;
end
end
fclose(fid) ;
iwant is the line number you wanted.

その他の回答 (1 件)

Orion
Orion 2016 年 3 月 24 日
Hi,
I guess you need something like that.
Assuming you have a .txt file : MyTextFiles.txt, that contains :
ruiez
gjrigj
rjigjri
I Need This Line and the rest of it ?
gjijri
pzepaz
you need a code like that :
% Open and read the content
Myfile = 'MyTextFiles.txt';
fid = fopen(Myfile);
Text = textscan(fid,'%s','delimiter','\n');
Text = Text{1};
fclose(fid);
% pattern to find at the beginning of a line
pattern = 'I Need This Line';
% analyze
found = 0;
for i = 1:length(Text)
if strncmp(Text{i},pattern,length(pattern))
found = i;
break;
end
end
% result
if found
fprintf('pattern at line %d\n',found)
else
fprintf('pattern not found')
end
Of course, you can optimize this code and add a for loop for all the txt files you need to analyse.

カテゴリ

Help Center および File ExchangeText Files についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by