Help with extracting certain lines from a text file?
22 ビュー (過去 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!