MATLAB: How to extract rows from a text file with a specific start

extract rowtext file

$GNRMC,083059.00,A,2948.16655,N,12133.72003,E,0.018,,280217,,,D*69
$GNVTG,,T,,M,0.018,N,0.034,K,D*36
$GNGGA,083059.00,2948.16655,N,12133.72003,E,4,12,0.90,5.0,M,10.9,M,1.0,0790*64
$GNGSA,A,3,23,27,16,14,26,31,,,,,,,2.00,0.90,1.78*19
$GNGSA,A,3,80,73,82,83,70,81,71,,,,,,2.00,0.90,1.78*1C
For example I have this kind of text file (it continues on for very long) and I want to extract only the rows starting with $GNGGA and write them all to another text file

Best Answer

% Parameter:
FileName = 'C:\Your data file.txt';
Key = '$GNGGA';
NewFile = 'C:\Fixed.txt';
% Import text file and select lines starting with the Key string:
Str = fileread(FileName);
CStr = strsplit(Str, '\n');
Match = strncmp(CStr, Key, length(Key));
CStr = CStr(Match);
% Create new file and write matching lines:
fid = fopen(NewFile, 'w');
if fid == -1
error('Cannot create new file: %s', NewFile);
end
fprintf(fid, '%s\n', CStr{:});
fclose(fid);