尝试比较两个文本文件,并根据信息创建第三个文本文件

Mag*_*nus 5 ruby parsing

我有两个文本文件,master.txt和926.txt.如果926.txt中有一行不在master.txt中,我想写一个新文件notinbook.txt.

我写了我能想到的最好的东西,但鉴于我是一个可怕的/新手程序员,它失败了.这就是我所拥有的

g = File.new("notinbook.txt", "w")
File.open("926.txt", "r") do |f|
  while (line = f.gets)
    x = line.chomp
    if
      File.open("master.txt","w") do |h|
      end
      while (line = h.gets)
        if line.chomp != x
          puts line
        end
      end
    end
  end
end
g.close
Run Code Online (Sandbox Code Playgroud)

当然,它失败了.谢谢!

der*_*erp 11

这应该工作:

f1 = IO.readlines("926.txt").map(&:chomp)
f2 = IO.readlines("master.txt").map(&:chomp)

File.open("notinbook.txt","w"){ |f| f.write((f1-f2).join("\n")) }
Run Code Online (Sandbox Code Playgroud)

这是我的测试:

926.txt

line1
line2
line3
line4
line5
Run Code Online (Sandbox Code Playgroud)

master.txt

line1
line2
line4
Run Code Online (Sandbox Code Playgroud)

notinbook.txt

line3
line5
Run Code Online (Sandbox Code Playgroud)


小智 0

使用: http: //raa.ruby-lang.org/project/compare/

或者

%x(比较文件1 文件2)

或者

http://github.com/myobie/htmldiff/