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

3 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Guillaume
Guillaume el 22 de Feb. de 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 comentarios
Kona
Kona el 22 de Feb. de 2016
I had two columns!! I concatenated them in one and the problem is solved! Thank you again!!!
Guillaume
Guillaume el 22 de Feb. de 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.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Get Started with MATLAB en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by