Merging text files according to time
古いコメントを表示
Hi,
I am using the following code to merge data from several text files in the directory into a single file
files=dir('*.txt');
fileout='merged.txt';
fout=fopen(fileout,'w');
for cntfiles=1:length(files)
fin=fopen(files(cntfiles).name);
while ~feof(fin)
fprintf(fout,'%s %d\n',fgetl(fin),cntfiles);
end
fclose(fin);
end
fclose(fout);
How do i megre text files according to the time it was created. For instance i have 4 files in a directory and in the merged texted file the first data should be from the 1st file created, the second is the second file created and so on....
回答 (1 件)
Astik Sachan
2019 年 8 月 8 日
Hi Shreenath,
What you want is to sort the files (variable) on the basis of Time
Here is the code to do that
files = dir('*.txt')
files = struct2cell(files)
files = files' % to transpose the cell created
[S , I] = sort(files(:,3)); % make sure if '3' is your Time Field
files = files(I,:) % sorted variable files
Enjoy your day!
Thanks
3 件のコメント
The field order returned by dir is not guaranteed, which makes this line very fragile:
files = struct2cell(files)
In fact, this line would likely cause a bug between versions that include the folder field and those without. Better, much more robust code would simply refer to the required field itself.
Shreenath Krishnamurthy
2019 年 8 月 8 日
Astik Sachan
2019 年 8 月 9 日
編集済み: Astik Sachan
2019 年 8 月 9 日
Try This then
files = dir('*.txt')
files = struct2table(files)
[S , I] = sort(files.datenum);
files = files(I,:)
This is based on Datenum that is a timestamp in Numeric Form.
カテゴリ
ヘルプ センター および File Exchange で File Operations についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!