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.
댓글 수: 0
답변 (2개)
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.
댓글 수: 0
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)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 String Parsing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!