如何逐行比较两个文件

How to compare two files line by line

我想检查两个文件 'file1.txt''file2.txt' 并打印共同的行。我该怎么做?以下是我在文件中的内容:

file1.txt:

 An insightful look into the scenario of academic integrity and its implications give us the major motivation
 for pursuing the subject. The issue holds utmost significance as the intellectual standards of an individual
 pursuing an academia a reestablished around his ability to produce authoritative work. Plagiarism is thus lethal.
 Every year a large number of students and scholars submit a huge volume of material to their respective mentors and professors

file2.txt:

An insightful look into the scenario of academic integrity and its implications give us the major motivation
 for pursuing the subject. The issue holds utmost significance as the intellectual standards of an individual 
pursuing an academia a reestablished around his ability to produce authoritative work. Plagiarism is thus lethal. 
Every year a large number of students and scholars submit a huge volume of material to their respective mentors and professors. 
Due to the sheer amount of text involved, a manual Result and conclusion follow where we present our observations and learning.

根据 Arup 的建议进行了编辑。

puts File.readlines("file1.txt") & File.readlines("file2.txt")

您还可以使用外部迭代器逐个比较来自不同文件的行对,如下所示:

lines1 = File.readlines('file1.txt').each
lines2 = File.readlines('file2.txt').each

begin
  i = 0
  while true
    puts "line #{i +=1 }:"
    puts line1 = lines1.next
    puts line2 = lines2.next
    puts "identical: #{line1 == line2 ? 'yes' : 'no'}\n\n"
  end
rescue StopIteration
end

如果您不关心前后空格,那么您可以使用String#strip - line1.strip == line2.strip。当到达任一文件的末尾时,循环将停止。

line1.strip == line2.strip 产生的输出如下:

line 1:
 An insightful look into the scenario of academic integrity and its implications give us the major motivation
An insightful look into the scenario of academic integrity and its implications give us the major motivation
identical: yes

line 2:
 for pursuing the subject. The issue holds utmost significance as the intellectual standards of an individual
 for pursuing the subject. The issue holds utmost significance as the intellectual standards of an individual 
identical: yes

line 3:
 pursuing an academia a reestablished around his ability to produce authoritative work. Plagiarism is thus lethal.
pursuing an academia a reestablished around his ability to produce authoritative work. Plagiarism is thus lethal. 
identical: yes

line 4:
 Every year a large number of students and scholars submit a huge volume of material to their respective mentors and professors
Every year a large number of students and scholars submit a huge volume of material to their respective mentors and professors. 
identical: no

line 5: