MATLAB: Find and extract lines from text file

findlines

Hi all. I have a txt file which shows a surgery procedure step by step. I need to find the lines with the information "New site", the file have around 23 lines with that information. I need to extract those line into an excel file.
fileId=fopen('C:\Users\G10040419\Desktop\Data 1\protokoll.txt','r'); %
while ischar(lineData)
lineData=fgetl(fileId); % anytime you use fgetl you read a line and next time you use it reads next
if ~isempty(strfind(lineData,'New site no'))
disp(lineData)
end
end
I wrote this part, but I am not sure how to continue. PS: I am new to programming and using Matlab.

Best Answer

>> str = fileread('protokoll.txt');
>> C = regexp(str,'[^\n\r]+New site no \d+ created[^\n\r]+','match');
>> C{:}
ans = 12:42:06 -- New site no 1 created( Depth: -10.0 mm )
ans = 12:42:40 -- New site no 2 created( Depth: -9.5 mm )
ans = 12:43:17 -- New site no 3 created( Depth: -8.5 mm )
ans = 12:44:01 -- New site no 4 created( Depth: -7.5 mm )
ans = 12:44:37 -- New site no 5 created( Depth: -6.5 mm )
ans = 12:45:09 -- New site no 6 created( Depth: -5.5 mm )
ans = 12:45:43 -- New site no 7 created( Depth: -4.5 mm )
ans = 12:46:24 -- New site no 8 created( Depth: -4.0 mm )
ans = 12:46:58 -- New site no 9 created( Depth: -3.5 mm )
ans = 12:47:32 -- New site no 10 created( Depth: -3.0 mm )
ans = 12:48:06 -- New site no 11 created( Depth: -2.5 mm )
ans = 12:48:48 -- New site no 12 created( Depth: -2.0 mm )
ans = 12:49:20 -- New site no 13 created( Depth: -1.5 mm )
ans = 12:50:04 -- New site no 14 created( Depth: -1.0 mm )
ans = 12:50:38 -- New site no 15 created( Depth: -0.5 mm )
ans = 12:51:13 -- New site no 16 created( Depth: 0.0 mm )
ans = 12:51:48 -- New site no 17 created( Depth: 0.5 mm )
ans = 12:52:17 -- New site no 18 created( Depth: 1.0 mm )
ans = 12:52:50 -- New site no 19 created( Depth: 1.5 mm )
ans = 12:53:22 -- New site no 20 created( Depth: 2.0 mm )
ans = 12:53:51 -- New site no 21 created( Depth: 2.5 mm )
ans = 12:54:28 -- New site no 22 created( Depth: 3.0 mm )
ans = 12:55:04 -- New site no 23 created( Depth: 3.5 mm )
ans = 12:56:08 -- New site no 24 created( Depth: 4.0 mm )
Then use xlswrite to save the cell array C to an excel file.
Related Question