csv_replace.rb
Wed Jan 02, 2008 · 117 words

A short Ruby script I've found to be quite useful. It replaces values of the first CSV column with the values in the second column inside any text file (but it was specifically meant for MySQL dumps). I often use it whenever an entity relationship changes in a webapp. Since it's just a fulltext find/replace it's also much less error-prone than actually trying to consider the references themselves.

#!/usr/bin/env ruby

# Replace values of column 1 with column 2


require 'csv'

def usage
  puts "Usage: csv_replace csvfile sqlfile"
  exit 1
end

if ARGV.length == 0
  usage
end

reader=CSV.open(ARGV[0], 'r')
reader.shift #skip first row

str=File.read(ARGV[1])

reader.each { |row| str = str.gsub(row[0], row[1]) }

puts str

reader.close()
exit 0

back · essays · credits ·