MATLAB: Search for rows in text file and delete them and the line before

delete lines

Dear all,
I have output files from another software that have long text file (about 400K lines). The software however throws some text in between the data and some processor info, example
0 1 2 3 4
1 2 3 4 5
78
chunk 16
3 4 5 6 7
4 5 6 7 8
and so on. There will be more than 80 occurrences of the wrong/unwanted lines (in the example line containing string chunk and the line before it (78))
So what I want to do is to open the file and delete all lines/rows that contain string chunk and the line before them.
Could you please help in the subject?

Best Answer

Provided the entire file would fit in memory,
S = fileread('NameOfTheFile.txt'); %read as string
newS = regexprep(S, '[^\n]+\nchunk[^\n]*\n', '', 'lineanchors');
fid = fopen('NewFile.txt', 'w');
fwrite(fid, newS);
fclose(fid);
Note: this will fail under the circumstance that the chunk line is the last line of the file and there is no trailing newline on that last line. It will not, however, fail under the circumstance that the line to be discarded and chunk line are the first two lines of the file.