MATLAB: How to search text file for string, and return the line

searchstringtextscan

Hello,
I need to find where in a file a string occurs, and grab the 5th and 6th values on the same line into 2 variables. Here's a sample of the data:
401 FxTB 2591.1675 15.3213 2569.5085 2619.7012 50.1926 kN
20.840 s 4.080 s
522 103
402 FyTB 0.8813 17.3074 -67.7260 64.5470 132.2730 kN
15.280 s 16.560 s
383 415
I don't know where the FxTB will occur, but I need to store the 2569.5085 and 2619.7012 in two variables. I was using this:
fmt = ['%*f %*s' repmat('%*f',1,2) '%f %f']; % skip snb#/snbName/2numbers, then read 2 values: sensor 401
v = cell2mat(textscan(fid2,fmt,1,'headerlines', 553-1));
…but the line doesn't always occur on line number 553.
Maybe I need to load the whole file into memory…since I do search for about 6 variables per file.

Best Answer

loading the file into memory is the easiest way.
If you split the loaded text into lines, then strfind() or regexp() can be used to do the searching.
With strfind() you would
mask = ~cellfun(@isempty, strfind(TextAsCells, 'FxTB'));
the_one_line = TextAsCells(mask);
You can do much the same with regexp()
mask = ~cellfun(@isempty, regexp(TextAsCells, 'FxTB'));
the_one_line = TextAsCells(mask);
However, you can also use regexp() in a way to extract the data values more directly, similar to the below.
If you do not split the loaded text into lines, then regexp() can be used to do the searching.
f56 = regexp(TextAsSingleLine, '(?<=FxTB\s+(\S+\s+){2})\S+\s+\S+','match');
which would return {'2569.5085 2619.7012'}
Or you could use
parts = regexp(TextAsSingleLine, '(?<=FxTB\s+(\S+\s+){2})(?<f5>\S+)\s+(?<f6>\S+)','names')
parts =
struct with fields:
f5: '2569.5085'
f6: '2619.7012'
to get it pre-split.
If it is always the same field numbers then you could use, for example,
parts = regexp(TextAsSingleLine, '(?<varname>(FxTB|FyTB|P7qT)\s+(\S+\s+){2})(?<f5>\S+)\s+(?<f6>\S+)','names')
which should match for variable names FxTB, FyTB, or P7qT with the matched name returned in the varname field of the resulting struct.
Related Question