Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove rows in file - Ruby

What is a clever way to remove rows from a CSV file in ruby where a particular value exists in a particular row?

Here's an example of a file:

350 lbs., Outrigger Footprint, 61" x 53", Weight, 767 lbs., 300-2080
350 lbs., Outrigger Footprint, 61" x 53", Weight, 817 lbs., 300-2580
350 lbs., Outrigger Footprint, 61" x 53", Weight, 817 lbs., 300-2580
350 lbs., Outrigger Footprint, 69" x 61", Weight, 867 lbs., 300-3080
350 lbs., Outrigger Footprint, 69" x 61", Weight, 867 lbs., 300-3080

Ideally, I'd want a new file created with only this:

350 lbs., Outrigger Footprint, 61" x 53", Weight, 767 lbs., 300-2080
350 lbs., Outrigger Footprint, 61" x 53", Weight, 817 lbs., 300-2580
350 lbs., Outrigger Footprint, 69" x 61", Weight, 867 lbs., 300-3080

when given this:

300-2580
300-3080
300-2080

so I know i can do this with sort filename|uniq -d but I'm trying to learn Ruby (somewhat painfully).

Thanks in advance, M

like image 837
MarkL Avatar asked Dec 17 '22 10:12

MarkL


1 Answers

You can use this to get the unique lines in an array in a csv file

File.readlines("file.csv").uniq
=> ["350 lbs., Outrigger Footprint, 61\" x 53\", Weight, 767 lbs., 300-2080\n", "350 lbs., Outrigger Footprint, 61\" x 53\", Weight, 817 lbs., 300-2580\n", "350 lbs., Outrigger Footprint, 69\" x 61\", Weight, 867 lbs., 300-3080\n"]

To write it to a new file, you can open a file in write mode, write this into the file:

File.open("new_csv", "w+") { |file| file.puts File.readlines("csv").uniq }

For comparing values, you can use split function on ",", to access each column like this:

rows = File.readlines("csv").map(&:chomp) # equivalent to File.readlines.map { |f| f.chomp }
mapped_columns = rows.map { |r| r.split(",").map(&:strip) }
=> [["350 lbs.", " Outrigger Footprint", " 61\" x 53\"", " Weight", " 767 lbs.", " 300-2080"], ["350 lbs.", " Outrigger Footprint", " 61\" x 53\"", " Weight", " 817 lbs.", " 300-2580"], .....]
mapped_columns[0][5]
=> "300-2080"

If you want more functionality, you are better off installing FasterCSV gem.

like image 198
rubyprince Avatar answered Dec 31 '22 19:12

rubyprince