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

13 次查看(过去 30 天)
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.

回答(2 个)

Adam Danz
Adam Danz 2018-8-13
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 2018-8-13
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)

类别

Help CenterFile Exchange 中查找有关 String Parsing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by