尝试比较两个文本文件,并根据信息创建第三个文件 [英] Trying to compare two text files, and create a third based on information

查看:81
本文介绍了尝试比较两个文本文件,并根据信息创建第三个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文本文件,master.txt和926.txt.如果926.txt中的某行不在master.txt中,则我要写入一个新文件notinbook.txt.

I have two text files, master.txt and 926.txt. If there is a line in 926.txt that is not in master.txt, I want to write to a new file, notinbook.txt.

我写了我能想到的最好的东西,但是考虑到我是一个糟糕的/新手程序员,它失败了.这就是我所拥有的

I wrote the best thing I could think of, but given that I'm a terrible/newbie programmer it failed. Here's what I have

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

当然,它会失败.谢谢!

Of course, it fails. Thanks!

推荐答案

这应该有效:

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")) }


这是我的考验:


This was my test:

926.txt

line1
line2
line3
line4
line5

master.txt

line1
line2
line4

notinbook.txt

line3
line5

这篇关于尝试比较两个文本文件,并根据信息创建第三个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆