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

4 views (last 30 days)
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)

Answers (1)

Jan
Jan on 22 May 2015
Edited: Jan on 22 May 2015
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);

Tags

Community Treasure Hunt

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

Start Hunting!