How do I store only the lines in a text file that contain a certain string?

I have a text file that I would like to read and I only want to display lines which start with a certain string. For example, the contents of the text file are:
FX = 698 FY = 96325 FZ = 987 MX = 87 MY = 96 MZ = 169 FX = 856 FY = 1234 FZ = 654 MX = 5916 MY = 1648 MZ = 4789
What I want to do is display only the numerical values for the lines in the text file which start with FY. Then I would like to output these values into another text file. How do I do this? Thanks!

 Accepted Answer

This is a fairly robust way to do it:
% Open the file for reading.
inputFullFilename = fullfile(pwd, 'test2.m');
fidInput = fopen(inputFullFilename, 'rt');
% Open the file for reading.
if fidInput == -1
message = sprintf('Could not open %s for reading', inputFullFilename);
uiwait(errordlg(message));
return;
end
% Open the file for writing.
outputFullFilename = fullfile(pwd, 'output.txt');
fidOutput = fopen(outputFullFilename, 'wt');
if fidOutput == -1
message = sprintf('Could not open %s for writing', outputFullFilename);
uiwait(errordlg(message));
return;
end
% Read first line.
thisLine = fgetl(fidInput);
% Define the pattern youi're looking for.
searchPattern = 'FY =';
% Loop over lines, checking for the search pattern.
% Bail out if there are more than 10,000 lines (fail safe to prevent infinite loop)
lineCount = 1; % Fail safe
while ischar(thisLine) && lineCount < 10000
if length(thisLine) >= length(searchPattern)
if strcmp(thisLine(1:length(searchPattern)), searchPattern)
% Found it. Print it out.
fprintf('%s\n', thisLine);
fprintf(fidOutput, '%s\n', thisLine(length(searchPattern)+1:end));
end
end
% Read next line
thisLine = fgetl(fidInput);
lineCount = lineCount + 1; % Increment fail safe
end
% Close files.
fclose(fidInput);
fclose(fidOutput);
winopen(outputFullFilename); % Windows only

More Answers (0)

Categories

Find more on Scripts 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!