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{:});
Best Answer