MATLAB: Export matched lines from two text files

exporttext file

I need to identify the same lines between the two text files, mwithrm21.txt and virgomrmdist.txt, based on column 7 of each files. These matches should then be exported into a new text file, while removing the matched lines from mwithrm21.txt.
I have attached the text files.
I drafted the code below:
content1 = fileread( 'mwithrm21.txt' ) ;
content2_rows = strsplit( fileread( 'virgomrmdist.txt' ), sprintf( '\n' )) ;
found = cellfun( @(s)~isempty(strfind(content1, s)), content2_rows ) ;
output_rows = content2_rows(found) ;
fId = fopen( 'similarvclf.txt', 'w' ) ;
fprintf( fId, '%s\n', output_rows{:} ) ;
fclose( fId ) ;
output_rows = content2_rows(~found) ;
fId = fopen( 'mwithrm21_new.txt', 'w' ) ; % Remove the '_new' for overwriting original.
fprintf( fId, '%s\n', output_rows{:} ) ;
fclose( fId ) ;
But, I do not know how to make it specific to only searching column 7 and then exporting the entire matched line to a new text file.

Best Answer

Here is a first draft. Test it and let me know if anything is unclear or doesn't work.
% - Read files content as strings.
content1 = fileread( 'mwithrm21.txt' ) ;
content2 = fileread( 'virgomrmdist.txt' ) ;
% - Extract last column of each content.
codes1 = regexp( content1, '[^|]+(?=(\s|$))', 'match' ) ;
codes2 = regexp( content2, '[^|]+(?=(\s|$))', 'match' ) ;
% - Matches codes.
[isMatch_1in2, match_posIn2] = ismember( codes1, codes2 ) ;
% - Split content. Careful, whatever generates these files still uses
% carriage returns (\r) only.
rows1 = strsplit( content1, char(13) ) ;
rows2 = strsplit( content2, char(13) ) ;
% - Output matches (version mwithrm21.txt). Use new line chars (\n) as
% joint instead of carriage returns, change if you prefer \r.
fId = fopen( 'matches.txt', 'w' ) ;
fwrite( fId, strjoin( rows1(isMatch_1in2), '\n' )) ;
fclose( fId ) ;
% - Output non-matching rows of file 1.
fId = fopen( 'mwithrm21_reduced.txt', 'w' ) ;
fwrite( fId, strjoin( rows1(~isMatch_1in2), '\n' )) ;
fclose( fId ) ;
% - Output non-matching rows of file 2. Eliminate matching rows first.
rows2(nonzeros( match_posIn2 )) = [] ;
fId = fopen( 'virgomrmdist_reduced.txt', 'w' ) ;
fwrite( fId, strjoin( rows2, '\n' )) ;
fclose( fId ) ;
EDITs :
  • Replaced match_posIn2(match_posIn2~=0) with nonzeros( match_posIn2 ) after reading an answer by Matt J in another thread that mentions NONZEROS.