Skip to content

Instantly share code, notes, and snippets.

@hiroshi-maybe
Created August 2, 2012 10:00
Show Gist options
  • Save hiroshi-maybe/3236029 to your computer and use it in GitHub Desktop.
Save hiroshi-maybe/3236029 to your computer and use it in GitHub Desktop.
Extract csv from DML in a specific format
#!/usr/bin/ruby
##################################################
#
# author: Hiroshi Kori
# Extract csv from DML in a specific format:
# INSERT INTO `table_name` (`column1`, `column2`, ..) VALUES
# (value1, value2, ..),
# (value1, value2, ..),
# (value1, value2, ..);
#
##################################################
dir = ARGV[0] || Dir::pwd
resultdir = dir+"/data"
Dir::mkdir resultdir unless File.exists? resultdir
Dir::glob(dir+"/*.sql").each {|fname|
f = open fname
content = f.read
content.scan(/INSERT\s+INTO\s+\`(\w+?)\`\s*?\((.*?)\)\s*VALUES\s*(.*?)\;/im) do |m|
table=$1
columns=$2
values=$3
open(resultdir+"/"+File.basename(fname,".sql")+"."+table+".csv", "w") do |f|
columns.gsub! "`", "\""
f.write columns+"\n"
values.scan(/\((.*)\)/) do |m|
f.write $1+"\n"
end
end
end
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment