Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to compare two text files, and create a third based on information

Tags:

parsing

ruby

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!

like image 254
Magnus Avatar asked Sep 29 '11 22:09

Magnus


2 Answers

This should work:

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
like image 164
derp Avatar answered Nov 09 '22 18:11

derp


You can do something like this:

master_lines = []
File.open("notinbook.txt","w") do |result|
  File.open("master.txt","r") do |master|
    master.each_line do |line|
      master_lines << line.chomp
    end
  end

  File.open("926.txt","r") do |query|
    query.each_line do |line|
      if !master_lines.include? line.chomp
        result.puts line.chomp
      end
    end
  end
end
like image 43
dbyrne Avatar answered Nov 09 '22 18:11

dbyrne