Help with extracting certain lines from a text file?

조회 수: 10 (최근 30일)
Taylor Gates
Taylor Gates 2018년 7월 21일
편집: Jan 2018년 7월 22일
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
Taylor Gates
Taylor Gates 2018년 7월 21일
I think that only extracted the x column of the vertex. How can we fix that? Sorry for not including format it is like "vertex -0.666852 -4.031210 5.684145"
Jan
Jan 2018년 7월 22일
@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?

댓글을 달려면 로그인하십시오.

답변 (1개)

Jan
Jan 2018년 7월 22일
편집: Jan 2018년 7월 22일
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);

카테고리

Help CenterFile Exchange에서 Characters and Strings에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by