How to extract specific rows from a text file?

22 次查看(过去 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

采纳的回答

infinity
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 个)

类别

Help CenterFile Exchange 中查找有关 Language Support 的更多信息

产品


版本

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by