How to extract specific rows from a text file?
14 次查看(过去 30 天)
显示 更早的评论
% Parameter:
FileName = 'C:\HP1.txt';
Key = ' MODE ';
NewFile = 'C:\HP1_ordered.txt';
% Import text file and select lines starting with the Key string:
Str = fileread(FileName);
CStr = strsplit(Str, '\n');
Match = strncmp(CStr, Key, length(Key));
CStr = CStr(Match);
% Create new file and write matching lines:
fid = fopen(NewFile, 'w');
if fid == -1
error('Cannot create new file: %s', NewFile);
end
fprintf(fid, '%s\n', CStr{:});
fclose(fid);
Hello,
I used this script to extract rows with a specific start, and now I need to extract from this last file in attachment only a series of rows with a specific index (for example I want only a row every 10 rows).
Can you help me?
Thanks,
Alberto
0 个评论
采纳的回答
infinity
2019-7-3
Hello,
Here is an solution that you can refer,
clear
FileName = 'HP1_ordered.txt';
NewFile = 'HP1_ordered_skip10.txt';
fp = fopen(FileName);
Str = textscan(fp,'%s','delimiter',sprintf('\f'));
fclose(fp);
cStr = char(Str{1}(1:10:end)); % you can change number of row
% that you want to skip at this line.
fid = fopen(NewFile, 'w');
if fid == -1
error('Cannot create new file: %s', NewFile);
end
for i = 1:size(cStr,1)
fprintf(fid, '%s\n', cStr(i,:));
end
fclose(fid);
In this code, it is supposed that you have "FileName" and want to write its containts into "NewFile". Also, you want to skip 10 rows of the "FileName".
Hope it could help.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!