将一行逗号分隔的字符串分隔为单独的行

时间:2014-07-02 04:56:49

标签: python ruby shell csv ubuntu

示例输入csv文件:

Email,Division,Department

预期产出:

Email,Division,Department

1 个答案:

答案 0 :(得分:0)

这是一种方法:

require 'csv'

csv = File.read('input_csv')

rows = csv.split("\n")
rows = rows.map do |i| 
    fields = i.parse_csv
    fields.map{ |j| j.include?(",") ? j.split(",")[1] : j}
end
puts rows.to_s
# [["Email", "Division", "Department"], ["john@example.com", "ux", "ui"], ["tom@example.com", "prod", "prod"], ["alex@example.com", "sales", "sales"]]

假设您要将行输出到输出CSV:

CSV.open("output.csv", "w") do |csv|
    rows.each { |row| csv << row }
end