How to read line by line from one file and find each line to another file and locate it?
10 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Guillaume
2016-2-22
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 个评论
Guillaume
2016-2-22
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.
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!