String search and delete in txt file

2 views (last 30 days)
Jason
Jason on 25 Mar 2011
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

Jan
Jan on 25 Mar 2011
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
Sebastian
Sebastian on 12 Apr 2012
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
Jan
Jan on 12 Apr 2012
@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

Find more on Migrate GUIDE Apps in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!