Printing specific lines to a text file

조회 수: 3 (최근 30일)
Danny Coles
Danny Coles 2013년 11월 14일
답변: Simon 2013년 11월 14일
Hi,
I need to split a text file into 2, so that I can write the first half of teh text file to a new text file, then insert some code into teh new text file that I have generated from Matlab, then insert the remaining half of teh original text file to teh new text file.
I have imported a text file (called subroutines.txt) and displayed it in Matlab using the following code:
% Read subroutines into Matlab
fileID = fopen('subroutines.txt'); T = textscan(fileID,'%s','Delimiter',' '); fclose(fileID); celldisp(T);
type subroutines.txt
This appears in the Matlab workspace as a 28712 x 1 cell. In the original subroutines.txt text file, there are 2524 lines of text, and by using the type subroutines.txt the data is displayed in Matlab correctly.
I would like to know how I can print half of the subroutines.txt text file to a new text file (lets call it new.txt).
Any help on this would be greatly appreciated.
Cheers
Danny

답변 (1개)

Simon
Simon 2013년 11월 14일
Hi!
If you read line by line with textscan, you should use '\n' as delimiter.
fid = fopen(FileName, 'r');
FC = textscan(fid, '%s', 'Delimiter', '\n');
fclose(fid);
FC = FC{1};
This gives you a cell array with as many cells as you have lines. Youmay write tham to a file using fopen/fclose and fprintf.

카테고리

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