Skip to content

Instantly share code, notes, and snippets.

@kejadlen
Created October 26, 2017 18:24
Show Gist options
  • Save kejadlen/89ce508ab2d487288f36b62d557a0926 to your computer and use it in GitHub Desktop.
Save kejadlen/89ce508ab2d487288f36b62d557a0926 to your computer and use it in GitHub Desktop.
require "csv"
filename, column_name, replacement, output = *ARGV[0..3]
csv = begin
CSV.read(filename, headers: true)
rescue
puts "input file missing"
exit 1
end
unless csv.headers.include?(column_name)
puts "column name doesn’t exist in the input file"
exit 1
end
CSV.open(output, "wb") do |out|
out << csv.headers
csv.each do |row|
row[column_name] = replacement
out << row
end
end
filename, column_name, replacement, output = *ARGV[0..3]
csv = begin
File.read(filename).split("\n")
rescue
puts "input file missing"
exit 1
end
headers = csv.shift
column_index = headers.split(?,).index(column_name)
if column_index.nil?
puts "column name doesn’t exist in the input file"
exit 1
end
out = csv.map { |row|
cols = row.split(?,)
cols[column_index] = replacement
cols.join(?,)
}
out.unshift(headers)
File.write(output, out.join("\n"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment