How to search text file for string, and return the line?
Show older comments
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.
Accepted Answer
More Answers (1)
Image Analyst
on 6 Nov 2016
A very simple way is to use fgetl() ans strfind():
fid = fopen('fgetl.m');
tline = fgetl(fid);
lineCounter = 1;
while ischar(tline)
disp(tline)
if strcmp(tline, 'FxTB')
break;
end
% Read next line
tline = fgetl(fid);
lineCounter = lineCounter + 1;
end
fclose(fid);
lineCounter is the line number where it occurred. Then you can parse tline to pull out any numbers you want from tline using sscanf() or textscan() or whatever.
5 Comments
Kyle Boyce
on 7 Oct 2020
Very helpful. Thank you!
Hamidreza
on 31 Aug 2022
This not working for a keyword in a line. only finds the works for whole line. What if we looking for only a key word?
Image Analyst
on 31 Aug 2022
taimour sadiq
on 1 Nov 2023
if contains(tline, 'FxTB', 'IgnoreCase', true)
%% How to replace this 'tline' containing 'FxTB' in file with some string 'Hello'
break;
end
filename_in = "test.txt";
filename_out = "test_modified.txt";
lines = readlines(filename_in);
lines(contains(lines,'fxtb','IgnoreCase',true)) = "Hello";
writelines(lines,filename_out);
% check the input and output files:
type(filename_in);
type(filename_out);
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!