MATLAB Answers

Take an specific number from text file

2 views (last 30 days)
Julio
Julio on 18 Dec 2019
Edited: Bhaskar R on 18 Dec 2019
Hi,
I have hundreds of .txt files formatted like below. How can I take the 0.0100 number in the 4th row. Thanks for your help.
PEER NGA STRONG MOTION DATABASE RECORD
Taiwan SMART1(25), 9/21/1983, SMART1 I01, NS
ACCELERATION TIME SERIES IN UNITS OF G
NPTS= 1998, DT= .0100 SEC,
.2176017E-03 .2180801E-03 .2201622E-03 .2237002E-03 .2276644E-03
.2305577E-03 .2312295E-03 .2291726E-03 .2239502E-03 .2158447E-03
.2049926E-03 .1944003E-03 .1921357E-03 .2041462E-03 .2334501E-03
.2849964E-03 .3603396E-03 .4569771E-03 .5694626E-03 .6877673E-03
.7994576E-03 .8892554E-03 .9330067E-03 .9196535E-03 .8624011E-03

  2 Comments

per isakson
per isakson on 18 Dec 2019
Is that the only number that appears between the strings, DT= and SEC ?
Is it always the 4th row?

Sign in to comment.

Answers (2)

Bhaskar R
Bhaskar R on 18 Dec 2019
Edited: Bhaskar R on 18 Dec 2019
Suppose your data is in the text file datafile.txt
txt = fileread('datafile.txt');
val = str2num(cell2mat(erase(extractBetween(txt, 'DT', 'SEC'), '=')));

  1 Comment

Julio
Julio on 18 Dec 2019
It worked well. Just had to change t by txt in val. Thank you.

Sign in to comment.


per isakson
per isakson on 18 Dec 2019
Edited: per isakson on 18 Dec 2019
Here is an m-file, which is possible to build on to read more items from the text files.
To test I created the three files, 'cssm_1.txt', 'cssm_2.txt', 'cssm_3.txt' which all contain the text of your question. I edited the DT-number. One problem is to come up with a pattern that matches your "hundreds of .txt files" and no other.
>> sas = read_Taiwan('d:\m\cssm\cssm_*.txt');
>> [sas.DT]
ans =
0.01 0.02 0.03
>> {sas.name}
ans =
1×3 cell array
{'cssm_1.txt'} {'cssm_2.txt'} {'cssm_3.txt'}
>>
where in one file named read_Taiwan.m
function sas = read_Taiwan( file_pattern )
sad = dir( file_pattern );
len = length( sad );
sas(1,len) = struct( 'name','', 'folder','', 'DT',[] );
for jj = 1 : len
sas(jj).name = sad(jj).name;
sas(jj).folder = sad(jj).folder;
sas(jj).DT = read_DT_( sad(jj) );
end
end
function num = read_DT_( file )
fid = fopen( fullfile( file.folder, file.name ), 'rt' );
[~] = fgetl( fid );
[~] = fgetl( fid );
[~] = fgetl( fid );
chr = fgetl( fid );
[~] = fclose( fid );
cac = regexp( chr, '(?<=DT=)[^S]+(?=SEC)', 'match' );
num = str2double( cac{:} );
end
Replacing the four last statements of read_DT_ by
txt = string( fgetl( fid ) );
[~] = fclose( fid );
str = extractBetween( txt, "DT=", "SEC" );
num = str2double( str );
makes a slightly more readable code. Thanks to Bhaskar R

  0 Comments

Sign in to comment.

Sign in to answer this question.

Tags