Help with extracting certain lines from a text file?
10 次查看(过去 30 天)
显示 更早的评论
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 个评论
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
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);
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Characters and Strings 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!