Reputation: 3405
I want to combine 'n' text files.
% Content of files ('its is just dummy code')
file1.txt
19.09.2015 1 2 3 4
file2.txt
20.09.20155 2 3 7
file3.txt
21.09.2015 6 9 3 8
file4.txt %empty file
[FileNames,PathName] = uigetfile('*.txt','Select the txt file', 'MultiSelect', 'on');
Ofilestr='combinefile.txt'; % open an empty file to merge all
fileID = fopen(Ofilestr,'w');
fclose(fileID);
nbfiles =length(FileNames);
for it=1:nbfiles
file=FileNames{1,it};
% system('copy file+Ofilestr Ofilestr') %% %% not working
system(['copy' file+Ofilestr 'Ofilestr']) %% %% not working
end
Any idea. Also another solution for this problem.
Upvotes: 1
Views: 549
Reputation: 6187
Curiously I couldn't find a good duplicate for this on StackOverflow.
I presume by your use of copy
that you are looking for a solution for Windows. Coming from a Unix background, I would have used system(['cat ' FileNames{n} ' >> ' Ofilestr]);
. type
on Windows is supposed to be a near replacement for cat
so the following should accomplish your goal.
[FileNames, PathName] = uigetfile('*.txt', 'Select the txt file', 'MultiSelect', 'on');
Ofilestr = 'combinefile.txt';
fileID = fopen(Ofilestr,'w');
fclose(fileID);
for n = 1:numel(FileNames)
system(['type ' FileNames{n} ' >> ' Ofilestr]);
end
For a Unix solution, simply change type
to cat
.
If you want a portable version purely in MATLAB then this is what I would go with
[FileNames, PathName] = uigetfile('*.txt', 'Select the txt file', 'MultiSelect', 'on');
Ofilestr = 'combinefile.txt';
fileID = fopen(Ofilestr,'w');
for n = 1:numel(FileNames)
fwrite(fileID, fileread(FileNames{n}));
end
fclose(fileID);
Both solutions above result in the output file containing
19.09.2015 1 2 3 4
20.09.20155 2 3 7
21.09.2015 6 9 3 8
Note: I would not recommend using
Ofilestr = 'combinefile.txt';
fileID = fopen(Ofilestr,'w');
fclose(fileID);
to empty the contents of the file. I would instead adapt the above code to
[FileNames, PathName] = uigetfile('*.txt', 'Select the txt file', 'MultiSelect', 'on');
Ofilestr = 'combinefile.txt';
if (numel(FileNames) > 1 || FileNames ~= 0)
system(['type ' FileNames{1} ' > ' Ofilestr]);
for n = 2:numel(FileNames)
system(['type ' FileNames{n} ' >> ' Ofilestr]);
end
end
Upvotes: 1
Reputation: 3042
how about this then?
A = [];
for ii = 1:length(files)
% load new contents
newA = load(files(ii).name, '-ascii');
% concatenate horizontally
A = [A newA]; %#ok
end
% save final output
save('outputFile.txt', 'A')
Anyways there seem to be many answeres to this question already
Here some other atempts to take in account:
http://www.mathworks.com/matlabcentral/answers/10916-combine-multiple-text-files-into-one-text-file
Upvotes: 1