I need to transfer lines between two text files into a new text file. The text file in which I need to match lines is called m21rmmorphU.txt, and I need to match the lines belonging in the text file,virgoclusterrm.txt, that also belong in m21rmmorphU.txt, into a new text file.
So, I want to extract the lines that match in m21rmmorphU.txt from virgoclusterrm.txt into a new text file and remove the matched lines from m21rmmorphU.txt.
Files are attached.

 채택된 답변

Cedric
Cedric 2015년 8월 4일

0 개 추천

You can do something along this line:
content1 = fileread( 'm21rmmorphU.txt' ) ;
content2_rows = strsplit( fileread( 'virgoclusterrm.txt' ), sprintf( '\n' )) ;
found = cellfun( @(s)~isempty(strfind(content1, s)), content2_rows ) ;
output_rows = content2_rows(found) ;
fId = fopen( 'similar.txt', 'w' ) ;
fprintf( fId, '%s\n', output_rows{:} ) ;
fclose( fId ) ;

댓글 수: 4

jgillis16
jgillis16 2015년 8월 4일
편집: jgillis16 2015년 8월 4일
Thanks, but would there be any way to remove the lines found in similar.txt from m21rmmorphU.txt itself so that it doesn't contain those matched lines anymore?
Cedric
Cedric 2015년 8월 4일
편집: Cedric 2015년 8월 4일
See below
content1 = fileread( 'virgoclusterrm.txt' ) ;
content2_rows = strsplit( fileread( 'm21rmmorphU.txt' ), sprintf( '\n' )) ;
found = cellfun( @(s)~isempty(strfind(content1, s)), content2_rows ) ;
output_rows = content2_rows(found) ;
fId = fopen( 'similar.txt', 'w' ) ;
fprintf( fId, '%s\n', output_rows{:} ) ;
fclose( fId ) ;
output_rows = content2_rows(~found) ;
fId = fopen( 'm21rmmorphU_new.txt', 'w' ) ; % Remove the '_new' for overwriting original.
fprintf( fId, '%s\n', output_rows{:} ) ;
fclose( fId ) ;
Note that I permuted the files with respect to my first answer, so the 'm21..' file is split. Then we export rows that were found to the 'similar..' file, and rows that were not found to wherever you need to (including the original file if you want to overwrite it).
You are a gift :) Thank you!
Cedric
Cedric 2015년 8월 4일
편집: Cedric 2015년 8월 4일
My pleasure! You have been asking a lot of questions about the same file(s) lately, and often in a way which leads to answers that read file(s), perform one operation, and export file(s). This can be quite slow if you have many operations to perform. If the performance degrades too much, you may want to actually parse the input file, perform all the operations that you need to perform, and at the end export only once to file.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

태그

질문:

2015년 8월 4일

편집:

2015년 8월 4일

Community Treasure Hunt

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

Start Hunting!

Translated by