How to read line by line from one file and find each line to another file and locate it?
4 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Dear all,
I have 2 .csv files. The first thing i want to do is to read the first file line by line. All these lines are in the second file but in different row. I need to find where in the second file is each of the line (the number of line). Does anyone konw how to solve this problem?
Best regrds, Konstantina
0 Commenti
Risposta accettata
Guillaume
il 22 Feb 2016
A simple way:
leftcontent = strsplit(fileread('c:\somewhere\your\1stfile.csv'), {'\n', '\r'}); %read 1st file and split into lines
rightcontent = strsplit(fileread('c:\somewhere\your\2ndfile.csv'), {'\n', '\r'}); %read 1st file and split into lines
[foundinright, locationinright] = ismember(leftcontent, rightcontent)
locationinright contains the line number where each line of the first file is found in the second file (or 0 if not present), in the order of the lines in the first file.
3 Commenti
Guillaume
il 22 Feb 2016
It means that your version of matlab is older than R2013a (always a good idea to specify your matlab version if it's old), since that's where strsplit was introduced.
You can replace the code with:
findeol = sprintf('(?:%c|%c)+', 13, 10);
leftcontent = regexp(fileread('c:\somewhere\your\1stfile.csv'), findeol, 'split'); %read 1st file and split into lines
rightcontent = strsplit(fileread('c:\somewhere\your\2ndfile.csv'), findeol, 'split'); %read 1st file and split into lines
[foundinright, locationinright] = ismember(leftcontent, rightcontent)
which should work in versions < R2013a.
By the way don't accept an answer if it does not work for you.
Più risposte (0)
Vedere anche
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!