필터 지우기
필터 지우기

Merging text files according to time

조회 수: 1 (최근 30일)
Shreenath Krishnamurthy
Shreenath Krishnamurthy 2019년 8월 8일
편집: Astik Sachan 2019년 8월 9일
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
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
Shreenath Krishnamurthy
Shreenath Krishnamurthy 2019년 8월 8일
Hi, I am having a couple of issues
  1. When i try Astiks code, in a directory containing 7000 files, the files are not sorted properly according to date if there are files from two months i.e 31 may and 1, 2june.
  2. I get files which contains the names of the files directory date created etc. How do i use this information now to write to a single text file. i.e how do i use 'files' in fopen to read all these files.
thanks for your help.
Astik Sachan
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Data Import and Export에 대해 자세히 알아보기

제품


릴리스

R2018b

Community Treasure Hunt

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

Start Hunting!

Translated by