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.
  1 件のコメント
Orazio Alberto Terracciano
Orazio Alberto Terracciano 2019 年 7 月 3 日
Thank you very much, it works!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLanguage Support についてさらに検索

製品


リリース

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by