How to extract specific rows from a text file?

조회 수: 21 (최근 30일)
Orazio Alberto Terracciano
Orazio Alberto Terracciano 2019년 7월 3일
% 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