Printing specific lines to a text file

2 views (last 30 days)
Danny Coles
Danny Coles on 14 Nov 2013
Answered: Simon on 14 Nov 2013
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

Answers (1)

Simon
Simon on 14 Nov 2013
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.

Community Treasure Hunt

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

Start Hunting!