How to merge defined (with specific variable names) text files located in a different folder?

조회 수: 1 (최근 30일)
I have a above 5000 txt data set in the "Data" folder. I would like to merge some specific files into one single text file by working from another folder. The text files have the country names, year and lane numbers. Let's say I would like to merge only the text files from Germany at 2015 and for lane 2. I tried to use "cat". It worked if there is no variables in the cat. But when I want to include the variables into the "cat" it did not work. Also is there a way I don't have to use cd to reach the file and come back where my script is located? Here is my code. I appreciate if anyone can help. Thank you.
Bea
%
Country='Germany';
Year ='2015';
Lane ='2'
cd ('Users/bea/Documents/Data')
!cat Country, '_', Lane, '*',Year, '*.txt'> GermanyMerged.txt
cd ('/Users/Bea/Documents)

답변 (1개)

Jan
Jan 2015년 5월 22일
편집: Jan 2015년 5월 22일
Country='Germany';
Year ='2015';
Lane ='2'
cd('Users/bea/Documents/Data')
Command = ['cat ', Country, '_', Lane, '*', Year, '*.txt > GermanyMerged.txt'];
system(Command);
Is there really the need to change back to the directory the script is located in?
Another method is to stay on the Matlab level:
Folder = 'Users/bea/Documents/Data';
FileList = dir(fullfile(Folder, [Country, '_', Lane, '*', Year, '*.txt']));
OutFID = fopen(fullfile(Folder, 'GermanyMerged.txt'));
if OutFID == -1, error('Cannot open file'); end
for k = 1:numel(FileList)
data = fileread(fullfile(Folder, FileList(k).name));
fwrite(OutFID, data, 'char');
end
fclose(OutFID);
  댓글 수: 1
Stephen23
Stephen23 2015년 5월 23일
Use sprintf to make it a bit clearer and robust:
Command = sprintf('cat %s_%s*%s.txt > GermanyMerged.txt', Country, Lane, Year);

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

카테고리

Help CenterFile Exchange에서 Automated Driving Toolbox에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by