How to combine 4 .txt files in a single.txt file?

I have 4 .txt files, they've the same number of lines, but different numbers of columns.
The number one is like:
A
B
C
D
The number 2 is like:
1 x
2 y
3 z
4 w
I'd like to put then like that:
A 1 x
B 2 y
C 3 z
D 4 w

 Accepted Answer

Jan
Jan on 16 Feb 2018
Edited: Jan on 19 Feb 2018
Create a list of file File at first. Then import the lines:
File = {'a1.txt', 'a2.txt', 'a3.txt', 'a4.txt'}; % Thanks Walter
numberOfFiles = length(File); %
C = cell(1, numberOfFiles);
for k = 1:numberOfFiles
C{k} = strsplit(fileread(File{k}), '\n');
end
% Now export the joined lines:
AllC = C{1};
for k = 2:numel(C)
AllC = strcat(AllC, {' '}, C{k}); % [EDITED] With a space as separator here
end
[fid, msg] = fopen('Outfile.txt', 'w');
if fid == -1, error('Cannot open file for writing: %s', msg); end
fprintf(fid, '%s\n', AllC{:});
fclose(fid);
[EDITED] in the code: strcat omits spaces except if they are in a cell string. Fixed now.

11 Comments

I named the files of a1.txt and a2.txt, however, replacing "numberOfFiles" with "a" I got the error: Variable undefined "a" or class "a"
You have 4 files. numberOfFiles should be set to 4. File should be set to a cell array containing the names of the files.
File = {'a1.txt', 'a2.txt', 'a3.txt', 'a4.txt'};
numberOfFiles = length(File);
Now It works, but only problem is: the file are not separated by space. I think this line is not working:
AllC = strcat(AllC, ' ', C{k}); % With a space as separator here
If the files has different numbers of columns, How can I adapt the code?
AllC = strcat(AllC, {' '}, C{k}); % With a space as separator here
Thanks, Walter. I've fixed the code. Unfortunately strcat omits spaces smartly, except if they are inside a cell string. It is a bad idea to let a string concatenation allow to crop the strings.
if I have many (1000 file) how to replace it: File = {'a1.txt', 'a2.txt', 'a3.txt', 'a4.txt'};
dinfo = dir('a*.txt');
File = {dinfo.name};
Note that if the names go a1.txt through a9.txt then a10.txt through a99.txt, then the above code is likely to put them together in the order a1.txt a10.txt through a19.txt a2.txt a20.txt through a29.txt a3.txt a30.txt through a39.txt and so on. This would not happen if the names were a001.txt a002.txt and so on.
To sort in numeric order see the File Exchange contributions about natural sort order.
what if i want the content from 2.txt continue from the end of 1.txt content?

Sign in to comment.

More Answers (0)

Categories

Find more on MATLAB Support Package for USB Webcams in Help Center and File Exchange

Asked:

on 15 Feb 2018

Commented:

on 20 Jun 2020

Community Treasure Hunt

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

Start Hunting!