How can I split a file at defined intervals into multiple files?

Hi Matlab Community,
I am trying to split a file (see example included) at defined line intervals, e.g. every 4th line and safe the sequence of lines in a new file with increasing numbers in the filename. For example, I am trying to split a file with 40 lines of text into 10 files with 4 lines each and name the resulting files 1.txt, 2.txt, 3.txt. etc.
I have not included code as my attempts have not resulted in anything useful.
I am very grateful for any help and suggestions how to achieve this.
Thank you,
Max

 Akzeptierte Antwort

Wan Ji
Wan Ji am 17 Aug. 2021
Bearbeitet: Wan Ji am 17 Aug. 2021
s = fileread('test.txt'); % read files to string s
k = find(s==newline); % find newline position
s = mat2cell(s,1, diff([0,k(4:4:end-1),numel(s)])); % split with every 4 newlines
fid = arrayfun(@(i)fopen([num2str(i),'.txt'], 'wt'),1:1:numel(s)); % get the fid
arrayfun(@(i)fprintf(fid(i),'%s',replace(s{i},newline,'')),1:1:numel(s)); % write to 1.txt 2.txt...
arrayfun(@(i)fclose(q(i)),1:1:numel(s));% close files

4 Kommentare

Hi Wan Ji,
Thanks a lot for your answer. The basic concept of what i am trying to achive works with your code. Is there a way to keep the original line format, because I think the mat2cell function puts the four original lines into one line in the split files:
1.txt:
Here is some textHere is some text aswellHere is some textHere is some text aswell
Should look like:
Here is some text
Here is some text aswell
Here is some text
Here is some text aswell
Thanks a lot,
Max
Try this, maybe it is a matter of matlab version, I have tested alright with matlab 2020a
s = fileread('test.txt'); % read files to string s
k = find(s==newline); % find newline position
s = mat2cell(s,1, diff([0,k(4:4:end-1),numel(s)])); % split with every 4 newlines
fid = arrayfun(@(i)fopen([num2str(i),'.txt'], 'wt'),1:1:numel(s)); % get the fid
arrayfun(@(i)fprintf(fid(i),'%s',s{i}),1:1:numel(s)); % write to 1.txt 2.txt...
arrayfun(@(i)fclose(q(i)),1:1:numel(s));% close files
Wan Ji
Wan Ji am 18 Aug. 2021
Bearbeitet: Wan Ji am 18 Aug. 2021
I'd like to have my answer accepted if this code helps you. many thanks in advace
Hi,
Thanks a lot. It worked now!
Max

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Gefragt:

am 16 Aug. 2021

Kommentiert:

am 18 Aug. 2021

Community Treasure Hunt

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

Start Hunting!

Translated by