combining two text file with 100 equal number of header and body text
1 view (last 30 days)
Show older comments
I am beginner for using matlab. I have two files each with 100 events formatted like below. Then I would like to combine them under each of the header in one file .
181123 1020 36.76 56.8409N 99.9979E 10.89 0.00 123 0.22
LS14RT 10.54LS13RT 11.84LS12RT 12.54LS11RT 12.54LS15RT 12.94LS16RT 14.54
LS67RT 15.34LS17RT 16.94LS45RT 18.84LS18RT 19.34LS44RT 20.04LS19RT 20.94
LS63RT 21.14CCGMRT 21.84LS22RT 23.04LS66RT 24.94LS39RT 25.14LS34RT 26.44
181123 1020 36.76 56.8409N 99.9979E 10.89 0.00 123 0.22
LS14RT 18.34LS13BT 20.64LS12BT 21.74LS11BT 22.04LS15BT 22.64LS16BT 25.04
LS67BT 26.24LS17BT 29.14LS45BT 32.44LS18BT 33.54LS44BT 34.34LS19BT 35.54
Like this. Is there any help on this please?
181123 1020 36.76 56.8409N 99.9979E 10.89 0.00 123 0.22
LS14RT 10.54LS13RT 11.84LS12RT 12.54LS11RT 12.54LS15RT 12.94LS16RT 14.54
LS67RT 15.34LS17RT 16.94LS45RT 18.84LS18RT 19.34LS44RT 20.04LS19RT 20.94
LS63RT 21.14CCGMRT 21.84LS22RT 23.04LS66RT 24.94LS39RT 25.14LS34RT 26.44
LS14RT 18.34LS13BT 20.64LS12BT 21.74LS11BT 22.04LS15BT 22.64LS16BT 25.04
LS67BT 26.24LS17BT 29.14LS45BT 32.44LS18BT 33.54LS44BT 34.34LS19BT 35.54
6 Comments
Guillaume
on 19 Apr 2019
The easiest way to make it completely clear is to attach two example text files to your question. It will also help answer what line ending and character encoding is used.
Accepted Answer
Andrei Bobrov
on 19 Apr 2019
z = dir('file*_.txt');
zn = {z.name};
n = numel(zn);
c = cell(n,1);
for jj = 1:numel(zn)
f1 = fopen(zn{jj});
k = textscan(f1,'%s','delimiter','\n');
fclose(f1);
c{jj} = k{:};
end
c = cat(1,c{:});
H = regexp(c,'^\d+.*','match','once');
lo = ~cellfun(@isempty,H);
[a,b,c1] = unique(H(lo),'stable');
O1 = accumarray(c1(cumsum(lo)),(1:numel(c))',[],@(x){c(sort(x))});
for jj = 1:numel(O1)
lo1 = ~cellfun(@isempty,O1{jj});
lo2 = circshift(lo1,1) & lo1;
lo2([1,end]) = true;
O1{jj} = O1{jj}(lo2);
end
out = cat(1,O1{:});
2 Comments
Walter Roberson
on 23 Apr 2019
The first line with the dir call looks for all .txt files in the current directory whose name starts with file, followed by anything, followed by _.txt . The first for loop then reads them all in.
It looks to me as if after this code, the variable out will contain a cell array of character vectors, each entry representing one line, with the lines already in the order that you would want to output them. The only thing I see missing is an empty line before each header.
From here I suspect you would
fid = fopen('new_file.txt', 'wt');
fwrite(fid, '%s\n', out{:});
fclose(fid)
More Answers (1)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!