How to find the lines of two words repeated many times in a .txt file

10 ビュー (過去 30 日間)
Abdelhadi To'ma
Abdelhadi To'ma 2014 年 10 月 23 日
コメント済み: Abdelhadi To'ma 2014 年 10 月 23 日
I'm trying to find a two words (DATA & END ) repeated many times in a .txt file how I can get their positions or in any lines they are exist because I want to bring the numbers which are between these two words
this is a part of the file
-- Coefficient of friction (for calculation of temperature) -- SchmierTyp 0:Oil 1:Grease 2:Dry :TABLE FUNCTION ReibKoef INPUT X SchmierTyp TREAT
DATA
1 2 3
0,01 0,02 0,03
END
-- Coefficient of friction (for calculation of temperature) -- SchmierTyp 0:Oil 1:Grease 2:Dry :TABLE FUNCTION ReibKoef INPUT X SchmierTyp TREAT
DATA
1 2 3
0,01 0,02 0,03
END
and I'm trying to do this by typing
haystack = fopen('h1.dat','r');
needle = 'DATA';
line = 0;
found = false;
while ~feof(haystack)
tline = fgetl(haystack);
line = line + 1;
if ischar(tline) && ~isempty(strfind(tline, needle))
found = true;
break;
end
end
if ~found
line = NaN;
end
Thanks in advance
  2 件のコメント
Guillaume
Guillaume 2014 年 10 月 23 日
At first glance, your code looks correct. It will find the first line that contains 'DATA'. So what exactly is the problem you are having?
Abdelhadi To'ma
Abdelhadi To'ma 2014 年 10 月 23 日
I want to find all the lines that have DATA and END to be able to extract the numbers between the DATA and the END lines

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

採用された回答

Michael Haderlein
Michael Haderlein 2014 年 10 月 23 日
You just have to extend your if-structure:
if ischar(tline)
if found
if strcmpi(tline,'END')
found=false;
else
mydata(end+1,:)=str2num(tline);
end
else
if strcmpi(tline,needle)
found=true;
end
end
end
I cannot test this code right now, but it should at least serve well as starting point. Of course, you have to initialize mydata at the beginning (mydata=[];).
  1 件のコメント
Abdelhadi To'ma
Abdelhadi To'ma 2014 年 10 月 23 日
thanks a lot for your help but I think that I have found a good way for doing it
fid = fopen('h1.dat', 'rt');
s = textscan(fid, '%s', 'delimiter', '\n');
idx1 = find(strcmp(s{1}, 'DATA'), :, 'first');
idxx1 = find(strcmp(s{1}, 'END'), :, 'first');
buffer = s{1}(idx1(1,1)+1:idxx1(1,1)-1);
dataTxt = sprintf('%s\n',buffer{:});
data = textscan(dataTxt,'%f %f %f');
d=cell2mat(data);
fclose(fid);

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangePhysical Units についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by