Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby CSV Compare Two CSV Files

Tags:

ruby

csv

I have two CSV files with the same headers. I'd like to compare these files and return entries that are missing from the second file. Here's an example:

file1.csv

fname,lname,city,state
Joe,Smith,Dallas,TX
Jane,Done,Baltimore,MD
Frank,Jones,Plano,TX

file2.csv

fname,lname,city,state
Joe,Smith,Dallas,TX
Jane,Done,Baltimore,MD

Here's my code:

# Returns True if a match is found
# and False if none is found
def find_in_csv(csv_text,search_column,search_string)
  csv_text.find {|row|
    return row[search_column] == search_string
  }
end

How do I extend this function to allow returning missing lines?

like image 505
Ken Jenney Avatar asked Sep 18 '26 06:09

Ken Jenney


1 Answers

This will return an array of rows which are present in file1.csv but missed in file2.csv

csv1 = CSV.read("file1.csv")
csv2 = CSV.read("file2.csv")

csv1 - csv2
like image 119
dismir Avatar answered Sep 20 '26 21:09

dismir