Help with extracting certain lines from a text file?
10 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I'm analyzing a lot of data and needing to extract and certain lines and put them into a new file. The lines I am trying to extract begin with 'vertex.' I would like to use a loop to loop through the whole file extracting lines that begin with vertex and put them into another new text document. How can I do this?
4 Kommentare
Jan
am 22 Jul. 2018
@Taylor: You have posted the search string "vertex." with a trailing dot. Is this wanted or a typo. Should we guess, what the "x column" is?
Antworten (1)
Jan
am 22 Jul. 2018
Bearbeitet: Jan
am 22 Jul. 2018
Str = fileread('Thinker.txt');
CStr = strsplit(Str, '\n');
match = strncmp(CStr, 'vertex ', 7); % or 'vertex.' ?
CStr = CStr(match);
"I think that only extracted the x column of the vertex" is not a clear description, but with a bold guess:
% An easy loop method:
for k = 1:numel(CStr)
s = CStr{k};
v = find(s == ' '); % or: strfind(s, ' ')
CStr{k} = s(1:v(2)-1);
end
Now export the cell string to a file again:
fid = fopen('File.txt', 'w');
if fid == -1, error('Cannot open file!'); end
fprintf(fid, '%s\n', CStr{:});
fclose(fid);
You mentioned, that you want to use a loop. Then:
inFID = fopen((InFile.txt', 'r');
outFID = fopen((InFile.txt', 'w');
if inFID == -1 || outFID == -1
error('Cannot open files!');
end
while ~feof(inFID)
s = fgetl(inFID)
if ~isempty(s) && strncmp(s, 'vertex ', 7);
v = strfind(s, ' ');
fprintf(outFID, '%s\n', s(1:v(2)-1));
% or this might be faster:
% fwrite(outFID, s(1:v(2)-1), 'char');
% fwrite(outFID, 10, 'char');
end
end
fclose(inFID);
fclose(outFID);
0 Kommentare
Siehe auch
Kategorien
Mehr zu Characters and Strings finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!