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

6 ビュー (過去 30 日間)
Bruno Souza
Bruno Souza 2018 年 2 月 15 日
コメント済み: Walter Roberson 2020 年 6 月 20 日
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

採用された回答

Jan
Jan 2018 年 2 月 16 日
編集済み: Jan 2018 年 2 月 19 日
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 件のコメント
Farhan Hakimi Anuar
Farhan Hakimi Anuar 2020 年 6 月 20 日
what if i want the content from 2.txt continue from the end of 1.txt content?

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeStructures についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by