Reading specific lines from multiple text files

2 ビュー (過去 30 日間)
fadzhi
fadzhi 2021 年 2 月 1 日
編集済み: dpb 2021 年 2 月 2 日
Hi all,
I am only interested in the numerical values of line 10 and line 11 of multiple text files. Right now, i am using below code, but with %s, i get complete string and with %f, i donot get any values. Will really appreciate some helop
clear;
D = 'T:\New\files';
S = dir(fullfile(D, '*.txt'));
N = length(S);
for k = 1:N
fid = fopen(fullfile(D,S(k).name), 'r');
linenum = 10;
h(k)= textscan(fid,'%s',1,'delimiter','\n', 'headerlines',linenum-1);
fid=fclose(fid);
end

採用された回答

dpb
dpb 2021 年 2 月 1 日
Ya' gotsa' skip the text to get to the floating point value...
...
T=cell2mat(textscan(fid,'%*s%f',1,'HeaderLines',linenum-1));
...
results in
>> T
T =
180
>>
  2 件のコメント
fadzhi
fadzhi 2021 年 2 月 2 日
Many thanks for your comment but i am running it over a loop for multiple text file but i getting an error
D = 'c:files';
S = dir(fullfile(D, '*.txt'));
N = length(S);
h = cell(N,1);
for k = 1:N
fid = fopen(fullfile(D,S(k).name), 'r'); % open file
linenum = 12;
h(k) = cell2mat(textscan(fid, '%*s%f', 1, 'Headerlines', linenum-1));
fclose(fid);
end
dpb
dpb 2021 年 2 月 2 日
編集済み: dpb 2021 年 2 月 2 日
...
h = zeros(N,1); % cell2mat() returns double, not cell
for k = 1:N
fid = fopen(fullfile(D,S(k).name), 'r'); % open file
linenum = 12;
h(k) = cell2mat(textscan(fid, '%*s%f', 1, 'Headerlines', linenum-1));
fclose(fid);
end
Also, you changed value of linenum which won't match with the sample file location for the tmperature record.
NB: the above will only retrieve a number from a record with a single text string before the floating point number;
Messlaenge Extensometer: 50.000 [mm]
will fail.
> cell2mat(textscan(fid,'%*s%f %*[^\n]',inf,'Delimiter',':','HeaderLines',5))
ans =
50.0000
12.5000
1.5000
0.1000
180.0000
7.5000
NaN
72.2000
>> fid=fclose(fid);
>>
returns the array beginning with Messlaenge Extensometer: 50.000 [mm]
Or, can return the leading string as well...
>> frewind(fid)
>> (textscan(fid,'%s%f %*[^\n]',inf,'Delimiter',':','HeaderLines',5))
ans =
1×2 cell array
{8×1 cell} {8×1 double}
>> ans{:}
ans =
8×1 cell array
{'Messlaenge Extensometer' }
{'Probenbreite' }
{'Probendicke' }
{'Dehnrate' }
{'Temperatur' }
{'Pruefgeschwindigkeit' }
{'Kennwerte(*1)' }
{'Elastizitaetsmodul E (*2)'}
ans =
50.0000
12.5000
1.5000
0.1000
180.0000
7.5000
NaN
72.2000
>>

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeData Type Conversion についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by