I want to compare two files line by line and count how many lines they have in common , I tried the code below , but it doesn't work , somehow MATLAB stops working , ">>" just disappear
f = fopen('nv.txt','at');
fid = fopen('test.txt');
k = 0;
while ~feof(fid)
s1 = fgetl(fid);
if ~isempty(s1)
while ~feof(f)
s2 = fgetl(f);
if ~isempty(s2)
if(strcmp(s1,s2))
k = k+1;
end
end
end
end
end
fclose(fid);
fclose(f);
disp(k);

1 Kommentar

Image Analyst
Image Analyst am 12 Mär. 2016
If the second line is missing in one of the files, (and the rest of the lines are just moved up one) then do you say that from line 2 on they are all different?
What if the lines are all there but in some different order?

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

MHN
MHN am 12 Mär. 2016
Bearbeitet: MHN am 12 Mär. 2016

0 Stimmen

f = fopen('nv.txt');
fid = fopen('test.txt');
k = 0;
while ~feof(fid)
s1 = fgetl(fid);
frewind(f) % start from the first line of the second file
if ~isempty(s1)
while ~feof(f)
s2 = fgetl(f);
if ~isempty(s2)
if(strcmp(s1,s2))
k = k+1;
end
end
end
end
end
fclose(fid);
fclose(f);
disp(k);

3 Kommentare

Zineb EL MORCHID
Zineb EL MORCHID am 12 Mär. 2016
Thank you,it works now. but I noticed that it compares all the lines except the first one of the second file
MHN
MHN am 12 Mär. 2016
Please use the "accepted answer" button. Are you sure? I run the program line by line and it compares every lines include the first one.
Zineb EL MORCHID
Zineb EL MORCHID am 12 Mär. 2016
Yes Thank you, it works , I find out that one of the lines starts with space.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Image Analyst
Image Analyst am 12 Mär. 2016

0 Stimmen

Did you try the Compare tool on the Editor tool strip?

2 Kommentare

Zineb EL MORCHID
Zineb EL MORCHID am 12 Mär. 2016
Not really,I actually want the code to use it as a function in my program. Thank you
Adam Danz
Adam Danz am 20 Nov. 2021
This is best approach.
Also see visdiff.

Melden Sie sich an, um zu kommentieren.

r r
r r am 11 Mai 2021

0 Stimmen

I have two files with similar data and I want to extract them into a file, and I also want to print the same line for the same data in the two files
Please help me
F1 = fopen('E.txt');
T1 = textscan(F1,'%s', 'delimiter', '\n');
fclose(F1);
F2 = fopen('G.txt');
tt2 = textscan(F2,'%s', 'delimiter', '\n');
fclose(F2);
T1s = char(T1{:});
T2s = char(T2{:});
[C,ix,ic] = intersect(T1s,T2s,'rows')
%%%%%%%%%%%%%%%%%%out Fiel :::
dlmwrite('R.txt',C,'%.6f');

Kategorien

Mehr zu Audio I/O and Waveform Generation finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 12 Mär. 2016

Kommentiert:

am 20 Nov. 2021

Community Treasure Hunt

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

Start Hunting!

Translated by