How to extract specific rows from a text file?

18 visualizaciones (últimos 30 días)
% 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

Respuesta aceptada

infinity
infinity el 3 de Jul. de 2019
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.

Más respuestas (0)

Categorías

Más información sobre Language Support en Help Center y File Exchange.

Productos


Versión

R2016a

Community Treasure Hunt

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

Start Hunting!

Translated by