MATLAB Answers

Robert
0

Merging Multiple text files

Asked by Robert
on 27 May 2015
Latest activity Commented on by Astik Sachan on 8 Aug 2019
I have 1505 text files, each 96x6. I want to be able to merge them such that file 2 is below file 1, file 3 is below file 2 etc all in the same text file.
I was previously given this code
files=dir('*.txt');
fileout='merged.txt';
fout=fopen(fileout,'w');
for cntfiles=1:length(files)
fin=fopen(files(cntfiles).name);
while ~feof(fin)
fprintf(fout,'%s %d\n',fgetl(fin),cntfiles);
end
fclose(fin);
end
fclose(fout);
At first it seemed to work but I found it jumbles the data a bit and I cannot use it.
Are there any alternatives?

  0 Comments

Sign in to comment.

3 Answers

Answer by Stephen Cobeldick on 27 May 2015
Edited by Stephen Cobeldick on 3 Jun 2015
 Accepted Answer

I had exactly the same issue, and solved it by writing a function called natsortfiles to sort file-names into order based on their number values (not just ASCII order). You can get it here:
And you can simply use it like sort:
B = {'test2.m'; 'test10-old.m'; 'test.m'; 'test10.m'; 'test1.m'};
sort(B) % not in numeric order!
ans = {
'test.m'
'test1.m'
'test10-old.m'
'test10.m'
'test2.m'}
natsortfiles(B) % correct numeric order:
ans = {
'test.m'
'test1.m'
'test2.m'
'test10.m'
'test10-old.m'}
You can use it with your code by doing something like this (outline only):
S = dir('*.txt');
fnm = natsortfiles({S.name});
for k = 1:numel(fnm)
fid = fopen(fnm{k},'rt');
... code here
fclose(fid);
end

  0 Comments

Sign in to comment.


Answer by Joseph Cheng
on 27 May 2015

Since you're just doing a complete copy and paste of the text files just read it in as binary and write it all. I had to put a \n after writing all the data for each file as i didn't have one at the last line of my file. Such that it would merge the last line of previous file with the first line of the current file.
files=dir('txt*.txt'); %additional filter so i didn't read in my merged file
fileout='merged.txt';
fout=fopen(fileout,'w');
for cntfiles=1:length(files)
fin=fopen(files(cntfiles).name);
temp = fread(fin,'uint8');
fwrite(fout,temp,'uint8');
fprintf(fout,'\n');
fclose(fin);
end
fclose(fout);

  4 Comments

Show 1 older comment
Joseph Cheng
on 27 May 2015
Ahh i misunderstood what you were saying about jumbling of data.
Follow below answer for the sorting of the files based on Name or Time or any other File Information

Sign in to comment.



I have a follow up question on this thread. I am using the code given above by Robert to merge multiple text files in a directory. I want to have one single file that writes the 1st created file as first 2nd created file as 2nd data and so on ?

  0 Comments

Sign in to comment.