Skip to content

Instantly share code, notes, and snippets.

@miau
Created September 15, 2011 15:50
Show Gist options
  • Select an option

  • Save miau/1219622 to your computer and use it in GitHub Desktop.

Select an option

Save miau/1219622 to your computer and use it in GitHub Desktop.
convert Oracle CSV to normal CSV
# Oracle で「set colsep ','」として出力された固定長 CSV を
# 通常の CSV に変換するスクリプト
#
# カレントディレクトリの *.csv に対して処理を行い、new_*.csv に結果を出力します。
# 先頭行のカンマ位置を基準にフィールドの区切りを検出するため、
# 先頭行のデータ部分にカンマが含まれないことを確認のうえ実行してください。
Dir.glob("*.csv").each do |file|
puts file
output = ""
File.open(file, "rb") do |f|
first = true
pattern = nil
f.each do |line|
if first
pattern = Regexp.new(line.chomp.gsub(/([^,\r\n]+)/) { "(.{#{$1.length}})" })
first = false
end
output << line.match(pattern).captures.map {|field|
'"' + field.strip.gsub('"', '""') + '"'
}.join(",") + "\r\n"
end
end
File.open("new_#{file}", "wb") do |f|
f.write output
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment