MATLAB Answers

How to read line by line from one file and find each line to another file and locate it?

4 views (last 30 days)
Kona
Kona on 22 Feb 2016
Commented: Guillaume on 22 Feb 2016
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 Comments

Sign in to comment.

Accepted Answer

Guillaume
Guillaume on 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 Comments

Kona
Kona on 22 Feb 2016
Dear Guillaume, thank you very much for the answer. I did what you propose and i had this error: Undefined function 'strsplit' for input arguments of type 'cell'. Do you Know what does it mean?
Kona
Kona on 22 Feb 2016
I had two columns!! I concatenated them in one and the problem is solved! Thank you again!!!
Guillaume
Guillaume on 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.

Sign in to comment.

More Answers (0)

Tags


Translated by