Azzera filtri
Azzera filtri

How to delete every nth lines in a .txt file?

13 visualizzazioni (ultimi 30 giorni)
Morgane Flament
Morgane Flament il 13 Ago 2018
Risposto: Walter Roberson il 13 Ago 2018
Hi!
How to delete every nth line in a text file using MATLAB?
Let's say I have a text file, in which I want to delete 4 lines, every 5 lines, starting at n=1:
data0
data1
data2
data3
data4
data5
data6
data7
data8
data9
data10
data11
... up to 500
The data in bold is the one I want to keep in the text file, and in Italic is the data I want to erase from my text file in Matlab.
So at the end I obtain a file with 100 values, and I deleted 400 values. Can I do that with Matlab? Thank you for your help.

Risposte (2)

Adam Danz
Adam Danz il 13 Ago 2018
You'll need to read the text file into matlab, then delete every nth row using something like
data(1:n:end,:) = [];
Then you'll need to write the data back to a text file or overwrite the one you read from.

Walter Roberson
Walter Roberson il 13 Ago 2018
filename = 'YourFile.txt';
newfilename = 'YourNewFile.txt'; %recommended to be a different file than the input file
S = regexp( fileread(filename), '\r?\n', 'split');
T = S(5:5:end);
fid = fopen(newfilename, 'wt');
fprintf(fid, '%s\n', T{:});
fclose(fid)

Community Treasure Hunt

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

Start Hunting!

Translated by