String search and delete in txt file

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

 Accepted 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.

3 Comments

Thanks Jan thats excellent. (the search was for matching part of a line, thanks for showing both cases)
Hi Jan,
thanks for the detailed answer before!!!
I have an additional question:
I'd like to screen a dokument and collect all values after a certain string.
The value stands periodically (alone) in the next line of a certain string.
How is it possible to collect all these values in an array?
Thanks a lot in advance,
kind regards
Sebastian
@Sebastian: Please post a new question in a new thread. Then explain this sentence more clearly: "The value stands periodically (alone) in the next line of a certain string." An example would be good.

Sign in to comment.

More Answers (0)

Categories

Asked:

on 25 Mar 2011

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!