MATLAB: String search and delete in txt file

file search string

How can i open a txt file using GUIDE and search for a line containing a certain string and then delete all lines before this? Thanks

Best Answer

GUIDE is a tool to create a GUI. Therefore you cannot open a file in GUIDE.
You can read a text file by:
FID = fopen(FileName, 'r');
if FID == -1, error('Cannot open file'), end
Data = textscan(FID, '%s', 'delimiter', '\n', 'whitespace', '');
CStr = Data{1};
fclose(FID);
Do you search for a line, which equals the string, or should the string be part of the line?
If string equals a complete line:
Index = find(strcmp(CStr, SearchedString), 1);
If string should be part of the line:
IndexC = strfind(CStr, SearchedString);
Index = find(~cellfun('isempty', IndexC), 1);
Common for both methods:
% Delete inital lines:
if ~isempty(Index)
CStr(1:Index - 1) = [];
end
% Save the file again:
FID = fopen(FileName, 'w');
if FID == -1, error('Cannot open file'), end
fprintf(FID, '%s\n', CStr{:});
fclose(FID);
If you prefer DOS line breaks for unknown reasons, open the file with 'wt' mode.