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

1 vue (au cours des 30 derniers jours)
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)

Réponses (1)

Jan
Jan le 22 Mai 2015
Modifié(e) : Jan le 22 Mai 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);
  1 commentaire
Stephen23
Stephen23 le 23 Mai 2015
Use sprintf to make it a bit clearer and robust:
Command = sprintf('cat %s_%s*%s.txt > GermanyMerged.txt', Country, Lane, Year);

Connectez-vous pour commenter.

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by