フィルターのクリア

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

13 ビュー (過去 30 日間)
Morgane Flament
Morgane Flament 2018 年 8 月 13 日
回答済み: Walter Roberson 2018 年 8 月 13 日
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 Center および File ExchangeString Parsing についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by